I am new to Jest and am trying to run a simple unit test just to ensure everything is set up correctly and have been running in to lots of issues troubleshooing errors during compile time.
When running the testing suite, Jest is successfully finding the file I am trying to test and generates the following Unexpected Identifier error message on line 1.
Any idea why this is? is something missing? I have been trying to troubleshoot this for quite some time.
/Users/foo/Sites/test/Test.spec.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Test from './Test.vue';
^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
Note, removing the import statements altogether runs the test successfully. However, the whole reason I set up Jest was to test vue components.
Test.vue
<template>
<div class="test">
</div>
</template>
<script>
export default {
name: 'test',
components: { },
data() {
return {
}
},
methods: {
helloWorld() {
return 'hello world';
}
}
}
</script>
Test.spec.js
import Test from './Test.vue'
describe('Test',() => {
it('test', () => {
expect(true).toBe(true);
});
});
package.json
"devDependencies": {
"#vue/test-utils": "^1.0.0-beta.25",
"axios": "^0.18.0",
"babel-core": "^6.26.0",
"babel-jest": "^23.6.0",
"babel-loader": "^7.1.2",
"cross-env": "^5.1.1",
"file-loader": "^2.0.0",
"jest": "^23.6.0",
"jquery": "^3.2",
"laravel-mix": "^2.0",
"lodash": "^4.17.4",
"popper.js": "^1.14.3",
"source-map-support": "^0.5.9",
"vue": "^2.5.7",
"vue-jest": "^3.0.0",
"vue-test-utils": "^1.0.0-beta.11",
"webpack": "^3.8.1"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"vue"
],
"transform": {
".*\\.(vue)$": "vue-jest",
"^.+\\.js$": "babel-jest"
}
}
You are using ES6 features in your test, namely the import statement, so you need to compile them down to ES5 using a preset.
Create a babel.config.js and add #babel/preset-env, like so,
//babel.config.js
module.exports = {
presets: ["#babel/preset-env"]
};
Next, in your package.json under the jest setting, let jest know where the root of your test code is located, and the module directories that will be recursively searched by jest, like so,
//package.json
"roots": [
"test"
],
"moduleDirectories": [
"test",
"node_modules"
],
Related
I'm integrating Jest into my react native app. For some reason, the tests are failing due to a module that I'm using in the app. react-native-keyboard-aware-scroll-view is causing the tests to fail because it is written in TypeScript. The rest of the app is JS only. Since I don't code in TS I'm not sure how to fix this issue. The error I'm getting is below.
FAIL Components/Instructions/__tests__/instructions.test.js
● Test suite failed to run
../../node_modules/#codler/react-native-keyboard-aware-scroll-view/index.js:3
import listenToKeyboardEvents from './lib/KeyboardAwareHOC'
^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
at Object.<anonymous> (node_modules/native-base/src/basic/Content.js:5:1)
Here is my babel.config.js:
module.exports = function (api) {
api.cache(true);
const presets = [ "module:metro-react-native-babel-preset", "#babel/preset-env", "#babel/preset-typescript" ];
const plugins = [ "#babel/plugin-proposal-class-properties" ];
return {
presets,
plugins
};
}
I have the following in my package.json:
"devDependencies": {
"#babel/plugin-syntax-class-properties": "^7.12.1",
"#testing-library/jest-native": "^3.4.3",
"#testing-library/react-native": "^7.1.0",
"babel-preset-expo": "^8.3.0",
"jest-expo": "^39.0.0",
"react-test-renderer": "^17.0.1",
"ts-jest": "^26.4.4",
"typescript": "^4.0.5"
},
"jest": {
"preset": "jest-expo",
"setupFilesAfterEnv": [
"#testing-library/jest-native/extend-expect"
],
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-clone-referenced-element|#react-native-community|expo(nent)?|#expo(nent)?/.*|react-navigation|#react-navigation/.*|#unimodules/.*|unimodules|sentry-expo|native-base|#sentry/.*)"
],
"collectCoverage": true,
"collectCoverageFrom": [
"**/*.{js,jsx}",
"!**/coverage/**",
"!**/node_modules/**",
"!**/babel.config.js",
"!**/jest.setup.js"
]
}
I added the TS dev imports to try and fix the TS errors but it did not work.
When I run the test, it thorws "unexpected token error at the code:
const wrapper = shallow(<WelcomeMessage/>");
The error is thrown at "(<". I have looked at a number of answers from stackoverflow and github but somehow I still cannot get it to work.
I have written jest tests. This is my first time writing a test case using enzyme and react. So I am not familar with the setup. I have installed: babel jest, react-dom, babel-plugin-transform-export-extensions, enzyme-adapter-react-16, react-test-renderer, #babel/preset-env, and #babel/core
package.json:
{
"private": true,
"version": "0.0.0",
"name": "example-jquery",
"devDependencies": {
"#babel/core": "*",
"#babel/preset-env": "^7.4.4",
"babel-jest": "^24.8.0",
"babel-plugin-transform-export-extensions": "^6.22.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"jest": "^24.8.0",
"jest-dom": "^3.1.4",
"jest-useragent-mock": "0.0.3"
},
"dependencies": {
"jest-puppeteer": "^4.1.1",
"jquery": "^3.4.1",
"jsdom": "^15.0.0",
"puppeteer": "^1.15.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.8.6"
},
"scripts": {
"test": "jest --verbose"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
jest.config.js:
module.exports = {
preset: 'jest-puppeteer',
"bail": 0,
setupFiles: ['<rootDir>/enzyme.config.js'],
moduleFileExtensions: ['js', 'json', 'jsx'],
transformIgnorePatterns: ['<rootDir>/node_modules/']
}
enzyme.config.js:
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
.babelrc:
{
"presets": ["#babel/preset-env"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
WelcomeMessage.test.js:
import React from 'react';
import { shallow } from 'enzyme';
// Components
import WelcomeMessage from './WelcomeMessage';
function setup() {
const props = {
imgPath: 'some/image/path/to/a/mock/image',
};
const wrapper = shallow(<WelcomeMessage />);
return { wrapper, props };
}
describe('WelcomeMessage Test Suite', () => {
it('Should have an image', () => {
const { wrapper } = setup();
expect(wrapper.find('img').exists()).toBe(true);
});
});
This line:
<WelcomeMessage />
is JSX which "just provides syntactic sugar for the React.createElement function".
Since JSX isn't actually valid JavaScript code it must be compiled into React.createElement calls.
This is done by the Babel plugin #babel/plugin-transform-react-jsx which is included as part of #babel/preset-react.
Add #babel/preset-react to your Babel config and that should resolve the issue.
I have the following Jest test:
import React from 'react';
import IndexSign from '../IndexSign';
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<IndexSign index={1}/>
).toJSON();
expect(tree).toMatchSnapshot();
});
The IndexSign component that I am calling calls this StyleSheet component:
import {StyleSheet} from 'react-native';
export default StyleSheet.create({
//some styles
});
For testing, I am using Gulp:
gulp.task('tests', () => {
process.env.NODE_ENV = 'test';
return gulp.src('src').pipe(jest({
}));
});
The problem is that when I run this test, I get:
● Test suite failed to run
Cannot find module 'StyleSheet' from 'react-native-implementation.js'
at Resolver.resolveModule (../node_modules/jest-resolve/build/index.js:142:17)
at Object.StyleSheet (../node_modules/react-native/Libraries/react-native/react-native-implementation.js:98:25)
at Object.<anonymous> (styles/Styles.js:5:13)
Any idea why this is happening?
Why is it searching for StyleSheet in react-native-implementation.js rather than react-native, which I imported?
And why can it not find StyleSheet?
I ran into the same issue. Adding
"jest": {
"preset": "react-native"
},
in the package.json fixed the error for me.
Incase you are keeping separate config file like jest.config.js. Add preset in it. Checkout the sample config file
module.exports = {
preset: 'react-native',
setupFiles: ['<rootDir>/__test__/setup.js'],
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|gif|png|mp4|mkv|avi|webm|swf|wav|mid)$': 'jest-static-stubs/$1'
},
globals: {
__DEV__: true
},
collectCoverageFrom: [
'**/src/**/*.{js,jsx}',
'!**/src/**/style.js',
'!**/src/**/index.js',
'!**/src/theme/**',
'!**/android/**',
'!**/ios/**',
'!**/node_modules/**',
'!**/scripts/**',
'!**/__test__/**'
],
verbose: true,
testPathIgnorePatterns: ['/node_modules/'],
testResultsProcessor: 'jest-sonar-reporter',
testURL: 'http://localhost/'
}
There are two ways of fixing this issue.
1. Make sure you don't have or delete any file called jest.config.js in your root folder.
2. If you want to have a custom jest.config.js file, make sure you have a preset node in it.
Like so:
module.exports = {
preset: "react-native",
verbose: true,
};
I was facing the same problem. Now it is resolved.
My package.json looks like this :
{
"name": "ReactNativeTDDStarterKit",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest"
},
"dependencies": {
"react": "16.8.3",
"react-native": "0.59.5"
},
"devDependencies": {
"#babel/core": "7.4.4",
"#babel/runtime": "7.4.4",
"babel-jest": "24.8.0",
"babel-preset-flow": "^6.23.0",
"babel-preset-react-native": "4.0.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"enzyme-to-json": "^3.3.1",
"jest": "24.8.0",
"metro-react-native-babel-preset": "0.54.0",
"react-dom": "^16.8.6",
"react-test-renderer": "16.8.3"
},
"jest": {
"preset": "react-native",
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"setupFiles": [
"<rootDir>/jest/setup.js"
]
}
}
I am using react-native 0.59.5, I did not reset .babelrc or jest.config.js manually, I just installed the dependencies. It automatically generated presets for me after the installation is completed. My babel.config.js looks like :
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
I followed instructions from this Link
I am primarily a C# backend developer and trying to learn Vue.js. I use Visual Studio 2017 + ASP.NET MVC (as API + one layout) + Vue.js + Webpack.
.vue single-page component files are loaded by vue-loader, and .js files are loaded by babel-loader with es2015 preset.
app.js is transpiled successfully into output dist/script.js file by Babel, but .vue files give me syntax errors whichever combinations I use. I have the same error even if my navigation.vue error is absolutely empty:
ERROR in ./assets/component/navigation.vue
Module build failed: SyntaxError: Unexpected token {
Task Runner Explorer content:
nagivation.vue:
<template>
<div>
{{ greeting }}
</div>
</template>
<script>
export default {
data: {
greeting: 'Hello World'
}
}
</script>
app.js:
import Vue from "../vendor/vue.js";
Vue.component("navigation", require("../component/navigation.vue"));
const app = new Vue({
el: "#app"
});
webpack.config.js:
module.exports = {
entry: "./assets/core/app.js",
output: {
filename: "./dist/script.js"
},
module: {
loaders: [
{
test: /\.js$/,
loader: "babel-loader",
exclude: /node_modules/,
options: {
presets: ["es2015"]
}
},
{
test: /\.vue$/,
loader: "vue-loader"
}
]
},
resolve: {
extensions: ["*", ".js", ".vue"]
},
plugins: [
new NotifierPlugin()
]
};
package.json:
{
"version": "1.0.0",
"name": "helloworld",
"private": true,
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-vue": "^1.2.1",
"clean-webpack-plugin": "^0.1.17",
"webpack": "^3.8.1"
},
"dependencies": {
"babel-core": "^6.26.0",
"babel-eslint": "^8.0.2",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"css-loader": "^0.28.7",
"eslint": "^4.10.0",
"eslint-cli": "^1.1.1",
"eslint-loader": "^1.9.0",
"eslint-plugin-react": "^7.4.0",
"vue-loader": "^13.5.0",
"vue-router": "^3.0.1",
"vue-template-compiler": "^2.5.3",
"webpack-notifier": "^1.5.0"
}
}
What can be a cause of such cryptic error? How people usually debug such errors?
The error likely isn't coming from your .vue file but from vue-loader itself. If you are using vue-loader >= 13.1 (and possibly one of the vue-loader 12 versions) then you will need to ensure you have node 6.2 or above on your machine, because vue-loader uses features that only became available in that version. You can check your node version by running:
node --version
If you can't update your node version then try installing one of the earlier releases of vue-loader by doing:
npm install vue-loader#13.0.1 --save-dev
And hopefully the error should go away.
As a side note, you should also start using babel-preset-env rather than babel-preset-2015 as that has now been (or is being) deprecated.
I'm getting error when trying to run test cases code.i am using react native with jest . all was working fine before upgrade 0.40 . now is 0.42 all my test cases stop working and getting error following error.
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component, Children, PropTypes } from 'react';
^^^^^^
SyntaxError: Unexpected token import
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
at Object.<anonymous> (node_modules/react-native-root-siblings/lib/AppRegistryInjection.js:3:22)
at Object.<anonymous> (node_modules/react-native-root-siblings/lib/SiblingsManager.js:3:27)
here is my .babelrc code
{
"presets": [
"react-native"
],
"plugins": [
"transform-decorators-legacy"
]
}
what is issue I am not getting .
I ran into very same problem with 0.42. I banged my head until I found a solution piece by piece.
You need to to write ignores in package.json. Example of mine:
"jest": {
"preset": "react-native",
"setupFiles": [
"<rootDir>/src/config/jest.js"
],
"transformIgnorePatterns": [
"<rootDir>/(node_modules)/(?!react-native|react-navigation|bugsnag-react-native)"
],
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/babel-jest"
}
And my /config/jest.js looks like:
jest.mock('Linking', () => ({
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
openURL: jest.fn(),
canOpenURL: jest.fn(),
getInitialURL: jest.fn().mockImplementation(() => new Promise((resolve) => resolve()))
}));
jest.mock('mobx-react/native', () => require('mobx-react/custom'));
jest.mock('react-native-mixpanel', () => ({
sharedInstanceWithToken: jest.fn(),
trackWithProperties: jest.fn()
}));
jest.mock('bugsnag-react-native', () => ({
Client: jest.fn(),
Configuration: jest.fn()
}));
I'm not guaranteed this solves all of your problems directly. However the idea is to ignore all the "evil-doers" (react-native-root-siblings in your case), thus avoiding such error messages.
I got solution
"jest": {
"preset": "react-native",
"transformIgnorePatterns": [
"node_modules"
],
"coveragePathIgnorePatterns": [
"node_modules"
],
"modulePathIgnorePatterns": [
"node_modules"
]
},
and in my devDependencies I have added "react-addons-test-utils",
"react-dom" ,
"devDependencies": {
"babel-core": "^6.17.0",
"babel-eslint": "^7.2.1",
"babel-jest": "^19.0.0",
"babel-loader": "^6.2.5",
"babel-plugin-transform-decorators": "^6.13.0",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2017": "^6.16.0",
"babel-preset-react": "^6.16.0",
"babel-preset-react-native": "^1.9.1",
"babel-preset-stage-0": "^6.16.0",
"enzyme": "^2.8.0",
"jest": "^19.0.2",
"npm": "^4.4.4",
"react-addons-test-utils": "^15.4.2",
"react-dom": "^15.4.2",
"react-test-renderer": "^15.4.2"
}
thats solved all issue .