React App with Jest - Jest encountered an unexpected token - reactjs

I'm trying to test a component using the react-test-renderer library and i'm getting this error.
Header.test.js:
import ReactShallowRenderer from "react-test-renderer/shallow";
import React from "react";
import Header from "../../components/Header/Header";
test("should render Header correctly", () => {
const renderer = new ReactShallowRenderer();
renderer.render(<Header />);
// Returning the render output of the jsx
console.log(renderer.getRenderOutput());
});
That's my jest config:
"jest": {
"verbose": true,
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.(css|scss|less)$": "jest-css-modules"
}
My babelrc:
{
"env": {
"development": {
"plugins": ["transform-es2015-modules-commonjs"]
},
"test": {
"plugins": ["transform-es2015-modules-commonjs"]
}
}
}

Related

Jest import issue for react js app with custom imports prefix for workerize-loader

I am facing an issue with setting up tests for react app with Jest.
I am using workerize-loader! library to import modules into webworkers.
On tests that use the import worker from workerize-loader!./path/to/file are barking on import of the test. I tried with a custom loader, in the jest.condig.js file but that did not work. When I run the default testing script provided by the react app setup it cannot find the imports in the files. But the code when it runs works alright.
I need help with importing the modules inside of the test suite of jest
Basic test
import React from "react";
import {cleanup, fireEvent, render } from "#testing-library/react";
import App from "./App";);
afterEach(cleanup);
test("basic test", () => {
const { container } = render(<App />);
const linkElement = container.firstChild;
expect(linkElement).toBeInTheDocument();
});
Configuration
jest.config.js
module.exports = {
preset: 'ts-jest',
verbose: true,
testEnvironmentOptions: {
url: 'http://localhost/'
},
testEnvironment: 'jsdom',
transform: {
'workerize-loader(\\?.*)?!(.*)': '<rootDir>/workerize-jest.js',
'^.+\\.(js|jsx)$': 'babel-jest',
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
unmockedModulePathPatterns: [
'node_modules',
],
moduleNameMapper: {
'workerize-loader(\\?.*)?!(.*)': 'identity-obj-proxy'
},
};
.babelrc
{
"plugins": [
"syntax-dynamic-import",
"#babel/transform-runtime"
],
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
},
"test": {
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
]
}
}
}
Error message on react-scripts test
Cannot find module 'workerize-loader!./workers/css.worker'
In file
> 2 | import worker from 'workerize-loader!./workers/css.worker';
workerize-jest.js
module.exports = {
process(src, filename) {
return `
async function asyncify() { return this.apply(null, arguments); }
module.exports = function() {
const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});
const m = {};
for (let i in w) m[i] = asyncify.bind(w[i]);
return m;
};
`;
}
};

Cannot use import statement outside a module react native elements

I am running into problems when trying to test a component with react-native-elements.
I am getting "Cannot use import statement outside a module" on import from react-native-elements.
My babel config is:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['#babel/plugin-proposal-numeric-separator'],
};
jest config:
"jest": {
"preset": "react-native",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"setupFiles": [
"<rootDir>/__tests__/testSetup.ts"
]
}
The test is:
import { Questionnaire } from './Questionnaire';
import { render } from '#testing-library/react-native';
describe('Questionnaire', () => {
it('Should render', () => {
const { container } = render(<Questionnaire setSessionState={jest.fn()} />);
expect(container).toMatchSnapshot();
});
});
Any help would be appreciated!

Unexpected token < in shallow in react typescript

I am using react + typescript + jest done the intial setup's but when i try to the run the test i am getting the following error:
const component = enzyme_1.shallow(<Dummy_1.default />).contains(<h1>Hello</h1>);
^
SyntaxError: Unexpected token <
Package.json
"jest": {
"setupFiles": [
"<rootDir>/tests/setup/test-shim.js",
"<rootDir>/tests/setup/test-setup.js"
],
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
"testMatch": [
"**/tests/*.(ts|tsx|js)"
]
},
Test file:
import React from 'react';
import { shallow } from 'enzyme';
import Dummy from '../src/Dummy';
it('renders dummy page', () => {
const component = shallow(<Dummy />).contains(<h1>Hello</h1>);
expect(component).toBeTruthy();
});
I have tried adding preset in jest but i got the same error only. I have not installed babelrc do i need to install it? I have created the app using create-react-app

Cannot setup `babel-plugin-rewire` for React tests

I'm trying to setup babel-plugin-rewire so that in my Jest tests I can generate a small test snapshot for a wrapper component instead of having a huge one with all the child components in it.
The settings seem all to be correct but I get the following error:
ReferenceError: Wrapper is not defined
at _get_original__ (app\components\Wrapper\tests\index.te
st.js:22:2168)
at _get__ (app\components\Wrapper\tests\index.test.js:22:
1912)
at Suite.<anonymous> (app\components\Wrapper\tests\index.
test.js:8:82)
at Object.<anonymous> (app\components\Wrapper\tests\index
.test.js:6:1)
at process._tickCallback (internal\process\next_tick.js:103:7)
package.json
"babel": {
"presets": [
[
"latest",
{
"es2015": {
"modules": false
}
}
],
"react"
],
"env": {
"test": {
"plugins": [
"babel-plugin-rewire",
"transform-es2015-modules-commonjs",
"dynamic-import-node"
]
...
"devDependencies": {
...
"babel-plugin-rewire": "^1.1.0",
webpack.base.babel.js
(common webpack configuration -same in webpack.basetest.babel.js)
module: {
loaders: [{
test: /\.js$/, // Transform all .js files required somewhere with Babel
loader: 'babel-loader?plugins=babel-plugin-rewire',
exclude: /node_modules/,
query: options.babelQuery,
},
My Test
for the Wrapper component that contains a Header child component:
import React from 'react';
import { shallow } from 'enzyme';
import Wrapper from '../index';
describe('<Wrapper />', () => {
console.log('Debugging >>> ' + JSON.stringify(Wrapper)); // Wrapper is defined but blows up here ##
// beforeEach(() => {
// Wrapper.__Rewire__('Header', class extends React.Component {
// render(){ return <div {...this.props}>TEST only the wrapper!!</div> }
// });
// })
// it('renders correctly', () => {
// const tree = shallow( <Wrapper myProps={testData.myProps} /> );
// expect(tree.html()).toMatchSnapshot();
// });
...
});
Thanks
UPDATE:
If I comment out in Wrapper the JSX where Header is used (even leaving the import for Header as it is) Wrapper.__Rewire__ becomes defined and therefore the beforeEach doesn't throw errors anymore.

React jest shallowRender getRenderOutput returning null

I've been studying React, and I tried to make a jest test with the shallowRender but always return null on shallowRenderer.getRenderOutput()
MyComponent.react.js
import React from 'react';
export default class MyComponent extends React.Component {
render() {
return <div>Hello World!</div>;
}
}
__test__/MyComponent.react.js
jest.dontMock('../MyComponent.react.js');
import React from 'react/addons';
import MyComponent from '../MyComponent.react.js';
var TestUtils = React.addons.TestUtils;
describe('MyComponent', () => {
it('test', () => {
let shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<MyComponent/>);
let vdom = shallowRenderer.getRenderOutput();
console.log(vdom);
expect(1).toEqual(1);
});
});
npm test
> jest-test#1.0.0 test /home/bruno/Stuffs/jest-test
> jest
Using Jest CLI v0.5.8
PASS __tests__/MyComponent.js (0.897s)
null
1 test passed (1 total)
Run time: 1.189s
package.json
{
...
"scripts": {
"test": "jest"
},
"devDependencies": {
"babel": "^5.8.23",
"babel-jest": "^5.3.0",
"jest-cli": "^0.5.8",
"react": "^0.13.3",
"skin-deep": "^0.6.1"
},
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"testFileExtensions": [
"es6",
"js"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react"
],
"moduleFileExtensions": [
"js",
"json",
"es6"
]
}
}
The automocking feature does not work with the ES2015 imports so, if you change your MyComponent import with require statement, your code should be work.
This is the Github issue.
jest.dontMock('../MyComponent.react.js');
import React from 'react/addons';
const MyComponent require('../MyComponent.react.js'); // This is the important line!!
var TestUtils = React.addons.TestUtils;
describe('MyComponent', () => {
it('test', () => {
let shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<MyComponent/>);
let vdom = shallowRenderer.getRenderOutput();
console.log(vdom);
expect(1).toEqual(1);
});
});

Resources