I want to apply a jest test to react component and I get an error that says:
Jest encountered an unexpected token
When I try to:
import moment from 'moment';
import './style.css'; //<----here
I try to mock css files and image objects and change the configuration:
// 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|less)$": "<rootDir>/__mocks__/styleMock.js"
}
}
}
My styleMock.js is:
module.exports = {};
My fileMock.js is:
module.exports = 'test-file-stub';
But I still get the error:
Jest encountered an unexpected token
and the error is in the same place as it was previously.
My jest is the latest version "24.8.0".
Anyone knows why?
i use this lib for that identity-obj-proxy
npm install identity-obj-proxy
change this line:
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
to this:
"\\.(css|less)$": "identity-obj-proxy"
Related
I can't get vue testing to work with vue-test-utils and jest. I created a clean new project with vue cli and added jest as follows, maybe someone can follow along and tell me what I'm doing wrong. (I'm following this installation guide: https://vue-test-utils.vuejs.org/installation/#semantic-versioning)
vue create jest-test
1.1. npm install
npm install --save-dev jest #vue/test-utils vue-jest
Added jest config to package.json:
{
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest"
}
}
}
npm install --save-dev babel-jest #babel/core #babel/preset-env babel-core#^7.0.0-bridge.0
Adjusted jest config to:
{
"jest": {
"transform": {
// process `*.js` files with `babel-jest`
".*\\.(js)$": "babel-jest" //<-- changed this
}
}
}
Adjusted babel config to:
module.exports = {
presets: [
'#vue/cli-plugin-babel/preset',
'#babel/preset-env' //<-- added this
]
};
Created example.test.js in a tests directory under the project root (jest-test/tests)
Added the following to this file:
import { mount } from '#vue/test-utils'
import HelloWorld from "#/components/HelloWorld";
test('displays message', () => {
const wrapper = mount(HelloWorld)
expect(wrapper.text()).toContain('Welcome to Your Vue.js App')
})
Added the following to the package.json scripts:
"jest": "jest"
npm run jest
Get the following error:
C:\Users\xxx\jest-test\tests\example.test.js:1
import { mount } from '#vue/test-utils'
^^^^^^
SyntaxError: Cannot use import statement outside a module
Same happens with Mocha or if I try it in an existing project. Is this a bug? I can't get it working, no matter what I do.
Edit: If I do it with Vue CLI, it works
https://vue-test-utils.vuejs.org/installation/#installation-with-vue-cli-recommended
You need to transform both *.vue files and *.js files.
I tried your setup and could reproduce the issue. But after altering jest.config.js to the following, the tests will run fine:
module.exports = {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
transform: {
'.*\\.js$':'babel-jest',
".*\\.(vue)$": "vue-jest"
},
moduleNameMapper: {
"#/(.*)": "<rootDir>/src/$1",
},
testEnvironment: 'jsdom'
}
I am trying to set up Jest with a NextJS application, currently in jest.config.js:
module.exports = {
testPathIgnorePatterns: ["<rootDir>/.next/", "node_modules/"],
setupFilesAfterEnv: ["<rootDir>/__tests__/setupTests.tsx"],
transform: {
"^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
}
};
In my setupTests.tsx I have:
import "#testing-library/jest-dom/extend-expect";
However when I run npm run test I get the following error:
Module identity-obj-proxy in the transform option was not found.
<rootDir> is: ....
If I remove the line in jest.config.js I get:
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".
globals.css:2
body {
^
SyntaxError: Unexpected token '{'
> 5 | import "../styles/globals.css";
What configuration should I use for the css and scss files?
** EDIT **
I made sure that identity-obj-proxy is in my devDependencies however, now I get an error:
Test suite failed to run
Test suite failed to run
TypeError: Jest: a transform must export a `process` function.
> 5 | import "../styles/globals.css";
| ^
6 | import React from "react";
You need to install identity-obj-proxy. Run >>> yarn add -D identity-obj-proxy
Try this:
Create a file style-mock.js with this content
module.exports = {};
Specify it inside the moduleNameMapper field of jest config
moduleNameMapper: {
'^.+\\.(css|less)$': '<rootDir>/jest-config/style-mock.js'
}
With this setup, it will mock all css import, hope it helps
I have already integrated Detox to my react native project (using yarn workspaces) and it works ok. But when I want to use import syntax the tests fail.
This is the error:
import { linkBarTest } from './helpers';
^^^^^^
SyntaxError: Unexpected token import
at ScriptTransformer._transformAndBuildScript (../node_modules/jest-runtime/build/script_transformer.js:403:17)
I didn't have this issue with a non-monorepo setup.
My config.json file:
{
"setupTestFrameworkScriptFile": "./init.js",
"testEnvironment": "node"
}
My babel.config.js file:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['jsx-control-statements'],
}
I've been trying to set up tests for some Angular components, but I keep running into an issue as all of my components use ng-lightning, which results in the following error:
/angular-lightning-test/node_modules/ng-lightning/ng-lightning.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){import
{ NgModule } from '#angular/core';
SyntaxError: Unexpected token import
I've tried multiple ways to get this going through Babel, though I'm not sure that should be required as Jest can handle it for every other file using import in this project.
I'm using jest-preset-angular to handle the setup for these tests. You can see the configuration it uses here.
I've created a very small sample project where you can see this error:
https://github.com/humantree/angular-lightning-test
The component is as simple as this:
#Component({
selector: 'badge',
template: '<ngl-badge>{{text}}</ngl-badge>'
}) export class BadgeComponent {
text = 'Test Badge';
}
and the test is as simple as this (I realize an actual test is missing, but the error still occurs before that would happen):
describe('BadgeComponent', () => {
let badge: BadgeComponent;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [BadgeComponent],
imports: [NglModule.forRoot()]
});
badge = TestBed.get(BadgeComponent).instance;
});
});
Can anyone see anything that I could add to my Jest configuration (or anything else) that would solve this error?
Note: For what it's worth, I also have these tests set up running in Mocha using mocha-webpack, and am having the exact same issue with that setup.
Thanks!
Try the following:
1) install the following packages: babel-jest, babel-preset-env
2) Add a .babelrc file at the your project root.
{ "presets": ["env"]}
3) Edit your jest.config.js file so babel process ng-lightning
{
"preset": "jest-preset-angular",
"transform": {
"^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
"^.+\\.js$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!ng-lightning)"
]
}
I have react component to test, I import its CSS using webpack as the following.
import styles from '../../node_modules/openlayers/css/ol.css' // eslint-disable-line no-unused-vars
After running jest I get error:
C:\Users\...\node_modules\openlayers\css\ol.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.ol-box {
^
SyntaxError: Unexpected token .
How to exclude css files from jest test suites?
Or better yet, add
yarn add --dev identity-obj-proxy
And add the following to jest.config.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|less|scss|sass)$": "identity-obj-proxy"
},
}
}
You can create your own mock in jest to prevent processing of css files.
// __mocks__/styleMock.js
module.exports = {};
Then in your package.json you can map any css files to the styleMock.js file under moduleNameMapper option:
"jest": {
...
"moduleNameMapper": {
...
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
},
..
},
See https://facebook.github.io/jest/docs/en/webpack.html#handling-static-assets
for more info.