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.
Related
I am trying to get jest to work with a new react-native project. However, when I run npm run test, I get the following error ReferenceError: __DEV__ is not defined. I've looked through countless Github issues and Stack Overflow posts regarding this but none of the suggestions have worked in my case.
Here is my jest.config.js file:
module.exports = {
transformIgnorePatterns: [
"node_modules/(?!(react-native|react-native-button|react-native-video)/)"
],
setupFiles: ['<rootDir>/__tests__/setup.json'],
}
package.json (notice I added DEV = true inside "jest")
{
"name": "DigitalSignagePlayer",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-async-storage/async-storage": "^1.15.5",
"axios": "^0.21.1",
"react": "^17.0.1",
"react-native": "0.64.2",
"react-native-fs": "^2.18.0",
"react-native-splash-screen": "^3.2.0",
"react-native-video": "^5.1.1"
},
"devDependencies": {
"#babel/core": "^7.14.5",
"#babel/preset-env": "^7.14.7",
"#babel/runtime": "^7.14.5",
"#react-native-community/eslint-config": "^2.0.0",
"babel-jest": "^27.0.2",
"eslint": "^7.28.0",
"jest": "^27.0.5",
"metro-react-native-babel-preset": "^0.66.0",
"react-test-renderer": "17.0.1"
},
"jest": {
"preset": "react-native",
}
}
bable.config.js
module.exports = {
presets: ['module:metro-react-native-babel-preset', '#babel/preset-env'],
};
metro.config.js
/**
* Metro configuration for React Native
* https://github.com/facebook/react-native
*
* #format
*/
module.exports = {
transformer: {
getTransformOptions: async () => ({
transform: {
experimentalImportSupport: false,
inlineRequires: true,
},
}),
},
};
I have tried setting globals.DEV = true and global.DEV = true at the top of my test files. I have tried adding setupFiles to jest.config.js which loads a setup.js file that contains global.DEV = true too. I have tried updating jest also. My current version of react-native is:
react-native-cli: 2.0.1
react-native: 0.64.2
I'm also using Metro, not Expo and I initially created the app with react-native-cli.
UPDATE:
setup.json
{
"globals": { "__DEV__": true }
}
UPDATE 2:
I changed setup.json to setup.js but I am still getting the same error:
global.__DEV__ = true
The variable is called __DEV__, so using DEV by trial and error doesn't make sense. Setting it in tests won't help because it won't affect the usage of the variable on import. In order to do this, this should have been done before tests in setupFiles* files.
Jes globals configuration option is supposed to do this. There should be "globals": { "__DEV__": true }. The configuration in package.json overridden by the configuration in jest.config.js. There should be only one of them (likely the latter), the other one needs to be removed.
I am trying to develop a custom reporter for mocha output that will be used with protractor. I have developed a good deal of the reporter and if I use the "--reporter" command line argument it works fine. However if I try to specify it in mocharc, or more importantly reporterOptions within the protractor configuration file it can't seem to find the package. Is the command line reporter flag the only way to specify a local/custom reporter? If not, how are you supposed to specify it outside of the command line?
.babelrc:
require:
- '#babel/polyfill'
- '#babel/register'
reporter: './mocha-reporter'
spec: '_src/js/tests/unit/**/*.spec.js'
package.json:
{
"name": "box",
"version": "1.0.0",
"description": "boom!",
"main": "index.js",
"scripts": {
"mocha": "mocha",
"mocha-custom": "mocha -O outputDir=_src/js/tests/reports,testDir=_src/js/tests/unit --reporter mocha-reporter",
"mochawesonme": "mocha --reporter mochawesome --reporter-options reportDir=_src/js/tests/reports,reportFilename=PCMS_unit_test_results",
"check-types": "tsc",
"clean-selenium": "webdriver-manager clean",
"update-selenium": "webdriver-manager update --standalone --versions.standalone=3.8.0",
"start-selenium": "webdriver-manager start --versions.standalone=3.8.0",
"integration-tests": "protractor protractor.conf.js"
},
"devDependencies": {
"#babel/cli": "~7.4.3",
"#babel/core": "~7.4.3",
"#babel/plugin-proposal-class-properties": "7.4.0",
"#babel/plugin-proposal-object-rest-spread": "~7.4.3",
"#babel/plugin-transform-destructuring": "~7.4.3",
"#babel/polyfill": "~7.4.3",
"#babel/preset-env": "~7.4.3",
"#babel/preset-typescript": "~7.3.3",
"#babel/register": "~7.4.0",
"#fortawesome/fontawesome-free": "5.8.1",
"#types/bluebird": "3.5.26",
"#types/jquery": "3.3.29",
"#types/knockout": "~3.4.65",
"#typescript-eslint/eslint-plugin": "~1.7.0",
"#typescript-eslint/parser": "~1.7.0",
"appcache-webpack-plugin": "~1.4.0",
"autoprefixer": "~9.5.1",
"babel-loader": "~8.0.5",
"chai": "~4.2.0",
"chai-as-promised": "7.1.1",
"copy-webpack-plugin": "~5.0.3",
"css-loader": "~2.1.1",
"eslint": "~5.16.0",
"eslint-config-airbnb-base": "~13.1.0",
"eslint-config-airbnb-typescript": "~3.0.0",
"eslint-plugin-import": "~2.17.2",
"file-loader": "~3.0.1",
"html-loader": "~0.5.5",
"html-webpack-plugin": "3.2.0",
"js-yaml": "~3.13.1",
"json-loader": "~0.5.7",
"jszip": "~3.2.1",
"karma": "~4.1.0",
"karma-chai": "~0.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-firefox-launcher": "~1.1.0",
"karma-mocha": "~1.3.0",
"karma-sinon": "~1.0.5",
"karma-webpack": "~3.0.5",
"mini-css-extract-plugin": "~0.6.0",
"mocha": "~6.1.4",
"mocha-reporter": "file:mocha-reporter",
"mochawesome": "~3.1.2",
"mochawesome-report-generator": "3.1.5",
"mochawesome-screenshots": "1.6.0",
"node-sass": "^4.12.0",
"popper.js": "~1.15.0",
"postcss-loader": "~3.0.0",
"protractor": "5.4.2",
"protractor-image-comparison": "3.1.0",
"sass-loader": "~7.1.0",
"sinon": "~7.3.2",
"style-loader": "~0.23.1",
"typescript": "~3.4.5",
"url-loader": "~1.1.2",
"webpack": "~4.30.0",
"webpack-cli": "~3.3.1",
"webpack-dev-server": "~3.3.1"
},
"dependencies": {
"bluebird": "~3.5.4",
"bootstrap": "3.3.7",
"d3": "~5.9.2",
"isomorphic-fetch": "2.2.1",
"jquery": "^3.4.0",
"jquery-ui": "~1.12.1",
"knockout": "~3.5.0",
"knockout-mapping": "~2.6.0",
"lodash": "~4.17.11",
"numeral": "~2.0.6",
"page": "~1.11.4"
}
}
index.js:
import mochaBaseReporter from 'mocha/lib/reporters/base';
import { takeScreenShot } from './javascript/screenShots';
import { populateTestResults } from './javascript/testTree';
import {
getFileContents,
writeToOutputFile,
} from './javascript/fileSystemAccess';
import {
getTemplate,
parseTestsIntoOutput,
addValuesToTemplate,
} from './javascript/templating';
import {
SUCCESS,
FAILURE,
FINISHED,
} from './constants';
const addStyle = template => getFileContents('styles.css')
.then(styles => addValuesToTemplate(template, { styles }))
.catch(error => console.log('file read of styles.css failed', error));
const createReport = (outputDirectory, fileName, data) => getTemplate('report')
.then(template => addValuesToTemplate(template, { 'test-suites': data }))
.then(template => writeToOutputFile(outputDirectory, `${fileName}.html`, template))
.catch(error => console.log('file read of template.html failed', error));
function mochaReporter(runner, environment) {
const tests = {};
const fileName = 'testfile';
const { outputDir, testDir, takeScreenShotOnFailure } = environment.reporterOptions || {};
const outputDirectory = outputDir && `${process.cwd()}/${outputDir}`;
const accumulateTestResults = (test, image) => populateTestResults(test, testDir, tests, image);
mochaBaseReporter.call(this, runner);
runner.on(SUCCESS, accumulateTestResults);
runner.on(FAILURE, test => (
takeScreenShotOnFailure && window
? takeScreenShot()
: Promise.resolve()
).then(image => accumulateTestResults(test, image)));
runner.on(FINISHED, () => {
parseTestsIntoOutput(tests)
.then(addStyle)
.then(template => addValuesToTemplate(template, runner.stats))
.then(html => createReport(outputDirectory, fileName, html))
.then(() => writeToOutputFile(
`${outputDirectory}/history`,
`test-run-${Date.now()}.json`,
JSON.stringify(tests),
));
});
return runner;
}
module.exports = mochaReporter;
protractor.conf:
/* eslint-disable global-require */
/* eslint-disable #typescript-eslint/no-var-requires */
const protractor = require('protractor');
const { join } = require('path');
const testDirectory = '_src/js/tests';
const baseDirectory = `${testDirectory}/integration/`;
// specifies whether tests will be run in parralel or not
const shardTestFiles = true;
// specifies how many browsers/drivers may be run in parralel
const maxInstances = 4;
function onPrepare() {
// register typescript file extensions with the babel compiler
require('#babel/register')({ extensions: ['.js', '.ts'] });
require('#babel/polyfill');
// don't wait for angular (since our app is currently not angular)
protractor.browser.waitForAngularEnabled(false);
// hot fix for protractor strange map behavior
// found here: https://github.com/angular/protractor/issues/2227#issuecomment-337249891
protractor.ElementArrayFinder.prototype.map = function mapHotFix(mapFn) {
return this.reduce((arr, el) => arr.concat(mapFn(el, arr.length)), []);
};
}
exports.config = {
// mocha configuration
framework: 'mocha',
mochaOpts: {
reporter: './mocha-reporter',
reporterOptions: {
outputDir: `${testDirectory}/reports`,
testDir: `${baseDirectory}/endToEnd`,
takeScreenShotOnFailure: true,
},
timeout: 600000,
slow: 3000,
},
seleniumAddress: 'http://localhost:4444/wd/hub',
// turn off promise management in favor of async/await
SELENIUM_PROMISE_MANAGER: false,
// spec config
specs: [`${baseDirectory}/endToEnd/**/*.spec.js`],
// browser configuration
timeout: 100000,
multiCapabilities: [
{
browserName: 'chrome',
shardTestFiles,
maxInstances,
chromeOptions: {
args: [
// 'show-fps-counter=true',
'--headless',
// '--disable-gpu',
'--window-size=1300,1000',
],
},
},
{
browserName: 'firefox',
shardTestFiles,
maxInstances,
'moz:firefoxOptions': {
args: [
'--headless',
],
},
},
],
onPrepare,
plugins: [
{
package: 'protractor-image-comparison',
options: {
baselineFolder: join(process.cwd(), `${baseDirectory}/screenshots/baseline/`),
screenshotPath: join(process.cwd(), `${baseDirectory}/screenshots/tmp/`),
formatImageName: '{tag}-{logName}-{width}x{height}',
savePerInstance: true,
autoSaveBaseline: true,
},
},
],
};
I could not find a way to load the local file directly, however I gave it a package.json and installed it directly to node_modules with npm. To be specific I ran
npm install ./mocha-reporter --save-dev
on my project directory after creating a package.json within the project folder. After some debugging I was able to solve my issue since the package was now a part of node's named packages.
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"
],
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'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 .