Reputation: 195
I've created a new repo that replicates this problem found here: https://github.com/davidRoussov/jest-webpack-alias
It's a React app bootstrapped using create-react-app, but it has been ejected. The error I'm getting when I run npm run test
is this:
FAIL src\components\Parent.test.js
● Test suite failed to run
Invariant Violation: Target container is not a DOM element.
at invariant (node_modules/fbjs/lib/invariant.js:42:15)
at Object.<anonymous> (src/index.js:7:20)
at Object.<anonymous> (src/components/Parent.js:2:14)
at Object.<anonymous> (src/components/Parent.test.js:2:15)
at process._tickCallback (internal/process/next_tick.js:103:7)
The component being tested, Parent.js:
import React, { Component } from 'react';
import Child from '@/components/Child';
class Parent extends Component {
render() {
return (
<div>
<Child/>
</div>
);
}
}
export default Parent;
The test, Parent.test.js:
import React from 'react';
import Parent from './Parent';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Parent/>
).toJSON();
expect(tree).toMatchSnapshot();
});
For the webpack config I've only added:
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
And:
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
'@': resolve('src')
},
The Jest config:
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx}"
],
"setupFiles": [
"<rootDir>/config/polyfills.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.js?(x)",
"<rootDir>/src/**/?(*.)(spec|test).js?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"
],
"moduleDirectories": ["node_modules"],
"modulePaths": ["src"],
"moduleNameMapper": {
"^@(.*)$": "<rootDir>/src",
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
},
Jest does not produce errors if import Child from '@/components/Child';
is replaced with import Child from './Child';
Upvotes: 0
Views: 720
Reputation: 400
I hope it's not too late, you forgot to substitute the captured regex groups in the path , like so:
"moduleNameMapper": {
"^@(.*)$": "<rootDir>/src/$1",
},
Upvotes: 1