How to debug React jest enzyme test cases - reactjs

When am trying to debug Rect Jest enzyme test cases in terminal, am getting the following error and am stuck because of that.
I created the app using create-react-app and following is my configuration:
.babelrc
{
"env": {
"test": {
"sourceMaps": "inline",
"presets": ["es2015", "react-app"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
}
}
Jest config from package.json
"jest": {
"testMatch": [
"**/src/**/?(*.)(spec|test).js?(x)"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"moduleFileExetnsions": [
"ts",
"txx",
"js",
"json"
],
"transform": {
"^.+\\.jsx$": "babel-jest",
"^.+\\.js$": "babel-jest"
}
}
Test case:
import { shallow } from 'enzyme';
import App from './App';
describe('App', () => {
it('should render app', () => {
const component = shallow(<App />);
expect(component).toMatchSnapshot();
});
});
Getting the following error:
Test suite failed to run
ReferenceError: [BABEL] .../src/containers/App.spec.js: Unknown option: /node_modules/babel-preset-react-app/index.js.overrides. Check out http://babeljs.io/docs/usage/options/ for more information about options.
A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:
Invalid:
`{ presets: [{option: value}] }`
Valid:
`{ presets: [['presetName', {option: value}]] }`
For more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options. (While processing preset: "/node_modules/babel-preset-react-app/index.js")
at Logger.error (node_modules/babel-core/lib/transformation/file/logger.js:41:11)
at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:226:20)
at node_modules/babel-core/lib/transformation/file/options/option-manager.js:265:14
at node_modules/babel-core/lib/transformation/file/options/option-manager.js:323:22
at Array.map (<anonymous>)
at OptionManager.resolvePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20)
at OptionManager.mergePresets (node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10)
at OptionManager.mergeOptions (node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14)
at OptionManager.init (node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12)
at File.initOptions (node_modules/babel-core/lib/transformation/file/index.js:212:65)
Edit:
Above error gone after changing "test" --> "dev" in .babelrc, but getting the another error:
"Jest encountered an unexpected token" at shallow(< App debug / >);

Try to use this .babel config:
{
"presets": ["es2015", "react-app"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
It should help you.

Related

Jest encountered an unexpected token in React (error by personal npm library)

I made a test code (just render and console)
import React from 'react';
import { render } from '#testing-library/react';
import { CheckExperienceHistory } from './CheckExperienceHistory';
import '#testing-library/jest-dom/extend-expect';
it('name validation', async () => {
beforeAll(() => console.log('--- start test ---'));
render(<CheckExperienceHistory />);
})
then, I got error when npm run test
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
/Users/stefancho/WebstormProjects/my-project/node_modules/wink_commons/dist/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as API from './api';
^
SyntaxError: Unexpected token *
12 | import Alert from 'antd/lib/alert';
13 |
> 14 | import { Download } from 'some-library';
| ^
15 |
16 | import {action} from '../../../redux/actions/index';
17 | import {api, service} from '../../configs/';
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (src/javascript/members/components/member/CheckExperienceHistory.js:14:1)
so I added tranformIgnorePatterns to package.json, but it didn't work (same error)
// package.json
"jest": {
"roots": [
"<rootDir>/src"
],
"collectCoverageFrom": [
"src/**/*.{js,jsx,ts,tsx}",
"!src/**/*.d.ts"
],
"setupFiles": [
"react-app-polyfill/jsdom"
],
"setupFilesAfterEnv": [
"<rootDir>/src/setupTests.js"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
"<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
],
"testEnvironment": "jest-environment-jsdom-fourteen",
"transform": {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^(?!.*\\.(js|jsx|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"node_modules/(?!(some-library)/)",
"^.+\\.module\\.(css|sass|scss)$"
],
"modulePaths": [],
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"web.js",
"js",
"web.ts",
"ts",
"web.tsx",
"tsx",
"json",
"web.jsx",
"jsx",
"node"
],
"watchPlugins": [
"jest-watch-typeahead/filename",
"jest-watch-typeahead/testname"
]
},
"babel": {
"presets": [
"react-app"
]
}
I think, jest attempt to parse some-library (this is personal library) but it failed to compile it, and I'm wondering why transformIgnorePatterns is not work.

jest with typescript throws an error when importing a file

I'm having issues with jest on typescript.
//myprovider.tsx
class MyProvider{
constructor(){}
giveMeFive(): int{ return 5; }
}
export { MyProvider }
// myprovider.test.js
import { MyProvider } from './myprovider';
test('give me five!', () => {
const myprovider = new MyProvider();
/// assert
})
I get the following error
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
import { MyProvider } from './myprovider';
^
I'm not sure what I'm missing, I have this on my package
//package.json
"jest": {
"transform": {
".(ts|tsx)": "<rootDir>/node_modules/ts-jest/preprocessor.js"
},
"testRegex": "(/tests/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": ["ts", "tsx", "js"]
},
// .babelrc
{
"presets": [
"#babel/preset-typescript"
]
}
//jest.config.js
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.tsx?$': 'babel-jest',
},
}
Make sure to install these packages:
babel-jest #babel/core #babel/preset-env
Your babel config should look like this:
presets: [
[
"#babel/preset-env",
{
targets: {
node: "current",
},
},
],
"#babel/preset-typescript",
]

JEST Test suite failed to run: TypeError: (0 , _reactRedux.connect) is not a function

So I want to test react components, and I just added testing library Enzyme and Jest, try to setup tests. But I got an error which come from my node modules if I import a component in my test code.
My app is using: React + Webpack + Babel.
I have "react": "^0.14.8","enzyme": "^3.3.0",, "enzyme-adapter-react-14": "^1.0.5" , "jest": "^22.4.2" , "webpack": "^3.8.1" , and "node": "5.6.0".
I installed Enzyme & Jest, wrote simple test like this and passed.
import enzyme, {shallow} from 'enzyme';
describe('Testing test', () => {
it('This test will always pass!', () => {
const test = "test"
expect(test).to.have.length(4);
})
})
This is Fine. BUT when I import components, just import, not even use it, I got an error:
(UPDATE: I feel the moduleNameMapper in package.json isn't correct)
import DealList from './DealList';
Test suite failed to run
TypeError: (0 , _reactRedux.connect) is not a function
35 | case("integer"):
36 | return integer
> 37 | case("required, integer"):
38 | return [required, integer]
39 | }
40 | }
at createConnectedField (node_modules/redux-form/lib/ConnectedField.js:329:43)
at createField (node_modules/redux-form/lib/createField.js:48:53)
at Object.<anonymous> (node_modules/redux-form/lib/Field.js:17:45)
at Object.<anonymous> (node_modules/redux-form/lib/index.js:122:14)
at Object.<anonymous> (src/components/CreateDealForm/CreateFundDealForm.js:37:18)
at Object.<anonymous> (src/components/index.js:24:28)
at Object.<anonymous> (src/containers/DealList/DealList.js:35:19)
at Object.<anonymous> (src/containers/DealList/DealList.test.js:7:17)
This is my package.json
"scripts" :{
...
"test": "jest"
},
"jest": {
"verbose": true,
"setupTestFrameworkScriptFile": "<rootDir>test/setup.js",
"moduleNameMapper": {
"components(.*)$": "<rootDir>/src/components"
},
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/redux-form/"
]
}
my .babelrc:
{
"presets": ["env", "stage-0", "react"],
"plugins": [
"syntax-dynamic-import",
"dynamic-import-node",
"transform-runtime",
"add-module-exports",
"transform-decorators-legacy",
"transform-react-display-name"
],
"env": {
"development": {
"plugins": [
"typecheck",
["react-transform", {
"transforms": [{
"transform": "react-transform-catch-errors",
"imports": ["react", "redbox-react"]
}
]
}]
]
},
"test": {
"presets": ["env", "stage-0", "react"]
}
}
}
my test/setup.js
import Enzyme from 'enzyme'
import Adapter from 'enzyme-adapter-react-14'
import { expect } from 'chai';
Enzyme.configure({ adapter: new Adapter() })
global.expect = expect;
Any thoughts would be awesome. Thank you!
I figured out that the moduleNameMapper on package.json is wrong.
This is correct:
"jest": {
"setupTestFrameworkScriptFile": "<rootDir>test/setup.js",
"moduleNameMapper": {
"^components(.*)$": "<rootDir>/src/components$1"
},
"verbose": true
},
And got another one which asks me to install the legacy decorators transform, but it is already installed. I will close this question.

Babel will not compile .test.js files while running Jest

While running yarn run jest --no-cache, An error is being thrown that says:
SyntaxError: Unexpected token import
My best guess is that babel is not reaching this this test file. Is their something special I need to include in .babelrc?
path:
/src/tests/LandingPage.test.js
test file:
import React from 'react';
import ReactShallowRenderer from 'react-test-renderer/shallow';
import LandingPage from '../../components/LandingPage';
test('Should render LandingPage correctly', () => {
const renderer = new ReactShallowRenderer();
renderer.render(<LandingPage />);
expect(renderer.getRenderOutput()).toMatchSnapshot();
});
.babelrc :
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}
Thanks #hannad rehmann for the nudge in the right direction here is the solution that worked for me.
Install babel-jest
yarn add babel-jest --dev
Configure .babelrc for test env
Jest automatically sets your Env to test, so duplicate whatever config you want to the test env.
{
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
],
"env": {
"test": {
"presets": [
"env",
"react"
],
"plugins": [
"transform-class-properties",
"transform-object-rest-spread"
]
}
}
}
Add jest.config.json to project root
{
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
Finally, let your test script know where to find config file
I just added it to my test script in package.json, but you can also just run this in the command line.
"scripts": {
"test": "jest --config=jest.config.json --watch"
},
oh. this issue had me waste so many days. here is what you need to do.
before that check these files.
1) .babelrc install corresponding modules and add them to package.json
define different env support as your jest always changes NODE_ENV to "test"
{
"presets": [
[
"env",
{ "modules": false }],
"react"
],
"plugins": [
"react-hot-loader/babel",
"transform-object-rest-spread",
"transform-class-properties",
"dynamic-import-webpack"
],
"env":{
"test":{
"presets": [
"env",
"react"
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties",
"dynamic-import-webpack"
]}
}
}
2) add this to your package.json
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"automock": false,
"transform": {
"^.+\\.jsx?$": "<rootDir>/node_modules/babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/"
],
"transformIgnorePatterns": [
"/node_modules/"
],
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"modulePathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"coverageReporters": [
"json",
"lcov",
"text"
]
}
What I understood about this problem is that Jest will change your NODE_ENV to "test" and Babel doesn't have any configuration for this env, we normally define Babel config for development and production env. When there is no babel transpilation, import keyword actually becomes undefined as it actually doesn't exist in JS context.
For anyone looking for solutions, in my case the problem turned out that I had my NODE_ENV environment variable configured to development for some reason.
Now JEST only sets the env to test if NODE_ENV is not defined yet, otherwise it'll use the value of NODE_ENV. This means if you have added in your .babelrc or babel.config file a dedicated part for the test (something like below), it will be ignored,and defaults (or the one matching your NODE_ENV) will be used instead!
{
...
"env": {
"test": { presets: [ "#babel/preset-env" ] }
}
...
}
So if it looks like JEST does not transform your test files (which one of a sign can be a SyntaxError: Cannot use import statement outside a module when running tests reated to your test.js or spec.js file) I'd recommend to check if you have NODE_ENV defined.
Use the env command (on MacOS and Linux or the appropriate command for your environment) to check the configured environment variables. If you have it already configured to something (other than test) you need to either remove that or prepend your jest commands with appropriate override: env NODE_ENV=test jest.
I hope it'll help others. Took me good few hours to figure out what was going on...

Unable to use webpack alias with Jest testing - Invariant Violation: Target container is not a DOM element

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';
I hope it's not too late, you forgot to substitute the captured regex groups in the path , like so:
"moduleNameMapper": {
"^#(.*)$": "<rootDir>/src/$1",
},
Link to the documentation

Resources