I'm trying to do some simple snapshot testing with jest and enzyme—moving to react-testing-library—for some react components that I am building.
When I run my tests the output contains a number of errors pointing to ES6/7 class properties.
My assumption was that I was missing babel-jest. I have followed the instructions to set that up but I am still receiving a number of errors from different components referring to a missing the babel transform...
See below:
Example Test:
import React from 'react';
import { render } from 'react-testing-library';
import HRWrapper from '.';
test('<HRWrapper> snapshot', () => {
const { container } = render(<HRWrapper>P.Body AaBbCc</HRWrapper>);
expect(container.firstChild).toMatchSnapshot();
});
Example Error:
● Test suite failed to run
.../packages/Tooltip/src/index.js: Missing class properties transform.
126 |
127 | class ToolTip extends React.Component {
> 128 | state = {
| ^
129 | active: false,
130 | style: {}
131 | }
Here is my configuration:
package.json:
{
...
"scripts": {
"postinstall": "npm run bootstrap",
"bootstrap": "lerna bootstrap",
"build": "lerna exec -- node ../../scripts/build.js",
"clean": "lerna clean",
"predev": "npm run alias",
"dev": "NODE_ENV=development start-storybook -p 9001 -c .storybook",
"docs": "for f in packages/*; do react-doc-generator $f/src -o $f/docs/README.md -e [*.story.js]; done",
"publish": "lerna --no-verify-registry publish",
"start": "npm run dev",
"test": "jest --json --outputFile=.jest-test-results.json",
"test:update": "jest --updateSnapshot",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"lint": "eslint .",
"fix": "eslint --fix",
"alias": "node scripts/alias.js"
},
"repository": {
"type": "git",
...
.babelrc:
{
"presets": [
"stage-1",
"react",
[
"env",
{
"modules": false
}
]
],
"plugins": ["transform-class-properties"],
"env": {
"test": {
"presets": ["env", "react"],
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
jest.config.js:
module.exports = {
"setupTestFrameworkScriptFile": "<rootDir>/config/setup-test.js",
"moduleNameMapper": {
[`#myLibrary/(.*)$`]: "<rootDir>/packages/$1/src"
},
"transform": {
"^.+\\.jsx?$": "babel-jest"
},
};
setup-test.js:
// this is the jest setupTestFrameworkScriptFile
/*
* use mocked classNames instead of unique hashed className generated by
* styled-components for snapshot testing
*/
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import 'jest-styled-components';
configure({ adapter: new Adapter() });
// here we set up a fake localStorage because jsdom doesn't support it
// https://github.com/tmpvar/jsdom/issues/1137
if (!window.localStorage) {
window.localStorage = {};
Object.assign(window.localStorage, {
removeItem: function removeItem(key) {
delete this[key];
}.bind(window.localStorage),
setItem: function setItem(key, val) {
this[key] = String(val);
}.bind(window.localStorage),
getItem: function getItem(key) {
return this[key];
}.bind(window.localStorage),
});
}
It's possible you also need stage-2 or stage-0.
See: https://github.com/tc39/proposals
Also remember that plugins are applied BEFORE presets, and presets are applied in order of last to first.
My colleague spotted the issue, one of those obvious ones staring me in the face...
transform-class-properties was missing from the plugins in my test environment configuration in my .babelrc.
I made the following changes and it now works properly.
.babelrc:
{
"presets": [
"stage-1",
"react",
[
"env",
{
"modules": false
}
]
],
"plugins": ["transform-class-properties"],
"env": {
"test": {
"presets": ["env", "react"],
"plugins": ["transform-class-properties", "transform-es2015-modules-commonjs"]
}
}
Related
I'm using Vite. I installed the npm plugin called 'vite-plugin-zip-file' in order to archive the dist folder. How can I run a separate from 'build' script in package.json specifically for this task?
vite.config.js below
import { defineConfig } from 'vite';
import { resolve } from 'path';
import { viteZip } from 'vite-plugin-zip-file';
export default defineConfig({
build: {
outDir: 'build',
},
plugins: [
viteZip({
folderPath: resolve(__dirname, 'build'),
outPath: resolve(__dirname),
zipName: 'Test.zip',
}),
],
});
package.json 'scripts' (I don't know what to write in 'zip' here)
"scripts": {
"dev": "vite",
"build": "vite build",
"serve": "vite preview"
"zip": ?
},
I tried adding the environmental variable, but I don't know exactly how to do it. So, there's probably another better way.
I am testing my backend with Jest, but I keep getting this error
\node_modules\generate-key\lib\generate.coffee:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){rn = (max) ->
^
SyntaxError: Unexpected token '>'
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
at Object.<anonymous> (node_modules/generate-key/index.js:2:18)
This is my jest config file:
module.exports = { clearMocks: true, coverageDirectory: 'coverage', testEnvironment: 'node',moduleFileExtensions: ['ts', 'js', 'json', 'node'] };
My test file:
/* eslint-disable no-undef */
const { getConvertedKind } = require('../common');
test('check', () => {
expect(3).toBe(3);
});
The imported function:
exports.getConvertedKind = kind => {
const kinds = {
cinemaPass: 'cinema',
hotelPass: 'hotel',
boardingPass: 'flight',
coupon: 'coupon',
eventTicket: 'event',
transit: 'transit',
storeCard: 'wallet',
offer: 'offer'
};
return kinds[String(kind)] || null;
};
package.json:
"scripts": {
"start": "nodemon server.js",
"start:prod": "NODE_ENV=production nodemon server.js",
"debug": "ndb server.js",
"test": "jest --config ./jest.config.js"
}
It seems like you're trying to load a .coffee file and by default jest doesn't transform node_modules.
You can check the transformIgnorePatterns option and try something like:
transformIgnorePatterns: ["node_modules/(?!generate-key)"],
I'm trying to get my jest tests to run. I am getting the error SyntaxError: Unexpected token export at the line export default configureStore..specifically on the word 'export'. To me this suggests redux-mock-store is not being transpiled by Babel, so how can I force this with Jest? I'm using jest-webpack.
ContractsActions.test.js
import * as contractsActions from './contractsActions';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
const store = mockStore({})
return store.dispatch(contractsActions.fetchAllContracts()).then(() => {
//Do something
})
});
package.json
...
"scripts": {
"test": "jest-webpack",
...
"jest": {
"transformIgnorePatterns": [
"!node_modules/"
]
}
...
webpack.config.js
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query:
{
presets:['es2015', 'react', 'stage-2']
}
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
}
},
I ended up fixing this problem by creating a separate .babelrc file, instead of trying to set the babel configuration settings in package.json. I'm sure there are other steps I tried that may have contributed but this seemed to be the one that fixed it.
.babelrc
{
"presets": [["es2015", {"modules": false}]],
"env": {
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}
Take a look at the package.json from that package:
https://github.com/arnaudbenard/redux-mock-store/blob/master/package.json
You can see it offers different entry points:
"main": "dist/index-cjs.js",
"module": "dist/index-es.js",
"js:next": "dist/index-es.js",
"browser": "dist/index.min.js",
Check if your node_modules/redux-mock-store has a dist folder. If not, start the build that suits your requirements (also listed in package.json):
"build:cjs": "babel src --out-file dist/index-cjs.js",
"build:umd": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f umd -c -i src/index.js -o dist/index-umd.js",
"build:umd:min": "cross-env BABEL_ENV=es NODE_ENV=production rollup -f umd -c -i src/index.js -o dist/index-umd.min.js",
"build:es": "cross-env BABEL_ENV=es NODE_ENV=development rollup -f es -c -i src/index.js -o dist/index-es.js",
"build": "npm run build:umd && npm run build:umd:min && npm run build:es && npm run build:cjs",
I don't know which of those versions buildable would be the right one for you, but I assume one of them will be. At worst, start npm i && npm run build:cjs in node_modules/redux-mock-store and resort to CommonJS require syntax:
const configureMockStore = require('redux-mock-store/dist/index-cjs.js');
Really hope this solves your problem, at least these are the steps I would try.
I try to test my react-native application using AVA and the babel-preset-react-native
My config looks like this:
"scripts": {
"test": "ava"
},
"ava": {
"files": [
"src/**/__tests__/*.js"
],
"failFast": true,
"require": [
"react-native-mock/mock.js",
"babel-register"
],
"babel": {
"presets": [
"react-native"
]
}
},
"devDependencies": {
"ava": "^0.13.0",
"babel-preset-react-native": "^1.2.4",
"babel-register": "~6.4.3",
"react-native-mock": "0.0.6"
}
…and fails like this:
/Users/zoon/Projets/xxxxx/node_modules/babel-register/node_modules/babel-core/lib/transformation/file/index.js:556
throw err;
^
SyntaxError: /Users/zoon/Projets/xxxxx/src/reducers/env.js: Unexpected token (12:8)
10 | case types.RECEIVE_CHANGE_ENV:
11 | return {
> 12 | ...state,
| ^
13 | current: Environments[action.env]
14 | };
15 | default:
If I export this babel config in a .babelrc file and use "babel": "inherit" in my AVA config, it fails in an other way:
/Users/zoon/Projets/xxxxx/node_modules/lodash-es/lodash.js:10
export { default as add } from './add';
^^^^^^
SyntaxError: Unexpected token export
I can't understand how to correctly configure this. I've tried Mocha, encountered the same problems.
babel-register ignores node_modules by default. You can set ignore:false in your .babelrc to disable that behavior. You could (probably should) also specify a more limited regular expression to avoid processing everything in node_modules.
See the docs: https://babeljs.io/docs/usage/require/
Your complete config should probably look something like this:
.babelrc
{
"presets": ["react-native"],
"ignore": false
}
package.json
{
"ava": {
"babel": "inherit"
}
}
I'm starting to learn ReactJS and I'm following instructions in a book on getting started. My directory structure looks like this:
app/App.js
node_modules
index.html
package.json
webpack.config.js
I think that the culprit of the problem is this error message from CLI:
ERROR in ./app/App.js
Module build failed: SyntaxError: c:/code/pro-react/my-app/app/App.js: Unexpected token (6:6)
4 | render() {
5 | return (
> 6 | <h1>Hello World</h1>
| ^
7 | );
8 | }
9 | }
The contents of App.js are:
import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1>Hello World</h1>
);
}
}
React.render(<Hello />, document.getElementById('root'));
Here is the contents of package.json:
{
"name": "my-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node_modules/.bin/webpack-dev-server --progress",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.4.5",
"babel-loader": "^6.2.1",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1"
},
"dependencies": {
"react": "^0.14.6"
}
}
And the contents of webpack.config.js are:
module.exports = {
entry: __dirname + "/app/App.js",
output: {
path: __dirname,
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel'
}]
}
};
I launch the application from CLI with the command:
npm start
And when I go to http://localhost:8080 in Dev Tools there is an error message:
GET http://localhost:8080/bundle.js 404 (Not Found)
But as I said, I think that the culprit is that it doesn't like the syntax so it doesn't make the bundle.js file. Please let me know what I'm doing wrong.
I think it happens because you are using babel-6 without babel presets, in this case you need babel-preset-es2015 and babel-preset-react.,
# For ES6/ES2015 support
npm install babel-preset-es2015 --save-dev
# Fot JSX support
npm install babel-preset-react --save-dev
then change webpack config
{
test: /\.jsx?$/,
loader: 'babel',
query: {
presets: ['es2015', 'react'],
}
}
or instead of using query you can create .babelrc file with content
{
"presets": ["es2015", "react"]
}
also you need install react-dom and use ReactDOM.render instaed or React.render