I'm new to testing React/Typescript apps.
command (alias for react-scripts test
):
yarn test
output:
FAIL src/containers/pages/Feature/Feature.test.tsx
● Test suite failed to run
Target container is not a DOM element.
17 | const { store, persistor } = configureStore(history, initialState);
18 |
> 19 | ReactDOM.render(
| ^
20 | <Provider store={store}>
21 | <PersistGate loading={null} persistor={persistor}>
22 | <ConnectedRouter history={history}>
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:27596:13)
at Object.render (src/index.tsx:19:10)
simple test code:
import * as React from 'react';
import { create } from 'react-test-renderer';
import Feature from "./Feature";
describe('Feature page component', () => {
test('matches the snapshot', () => {
const feature = create(
<Feature />,
);
expect(feature.toJSON()).toMatchSnapshot();
});
});
src/index.tsx file in fact contains ReactDOM.render()
call that fails in tests, but what's a working alternative?
Note: the app itself works fine, it's just failing to run in test mode.
in src/index.tsx file I have:
export const history = createBrowserHistory({
basename: '/admin',
});
const initialState: StoreState = (undefined as unknown) as StoreState;
const { store, persistor } = configureStore(history, initialState);
and then in services and sagas I import history
and store
from index.tsx. may it be the problem causing tests to fail?
I tried to extract history
and store
to a separate file (as suggested by commenters). Now the above code is inside src/initialState.ts
.
- Good news: error "Target container is not a DOM element" is gone!
- Bad news: I get a new error (which can be an independent problem, so extracted to a separate question)