React Native + jest + shallow rendering = unexpected token error - mobile

I'm trying to test a React Native component using jest and shallow rendering.
However, calls to ShallowRenderer.render() results in an error
SyntaxError: Unexpected token ...
at eval (native)
at Object.eval (components/list-conditions.js:1:244)
at Spec.eval (tests/components/list-conditions-test.js:14:48)
The test code is very simple, I don't even need to have an assert statement to get that error:
jest.dontMock('../../components/list-conditions.js');
const React = require('react');
const TestUtils = require('react-addons-test-utils');
const ListConditions = require('../../components/list-conditions.js');
describe('ListConditions', () => {
it('renders buttons', () => {
var renderer = TestUtils.createRenderer();
renderer.render(<ListConditions conditions={['a', 'b']} />);
});
});

I got the same Unexpected token error, and adding a .babelrc file in the project root file with the followings helps me
{
"presets": [
"react",
"es2015"
]
}

Related

Why do i get this error, Cannot use import statement outside a module

so im trying to make a test for my component a simple test that shows if the component was rendered
test('Should render the movie info', () => {
renderWithContext(<MovieInfo movie={mockMovies[0]} />);
expect(screen.getByText('Terrifier 2')).toBeInTheDocument();
});
but i get this error:
SyntaxError: Cannot use import statement outside a module
the problem seems to have be about axios some how because it happens when trying to import axios.
> 2 | import axios from 'axios';
| ^
i have a jest.config.js file like this.
const { compilerOptions } = require('./tsconfig.json');
const { pathsToModuleNameMapper } = require('ts-jest');
const { default: tsjPreset } = require('ts-jest');
module.exports = {
transform: {
...tsjPreset.transform,
'+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2|pdf)$':
'jest-transform-stub',
'^.+\\.ts?$': 'ts-jest',
},
moduleDirectories: ['src', 'node_modules'],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
transformIgnorePatterns: ['node_modules/(?!(axios)/)'],
};
and i have installed ts-jest, #types/jest and jest-transform-stub as dependencies
i have looked on the internet and this seems to be about some jest config that im doing wrong but nothing i do works
I solved this by adding this to my package.json i think its a hacky way of doing it but is the only way it worked for me.
"test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\"",

import 'useAuthenticator' from aws-amplify outputs "TypeError: window.URL.createObjectURL is not a function" when jest testing

I would like to know how to mock this kind of dependency's error. If I omit this import and comment out related source code, the test process is going to be fine. Already have got through Mock Function Jest, but no idea what I should do.
*This project was created by CRA with template typescript.
App component.
import { useAuthenticator } from '#aws-amplify/ui-react';
const App = () => {
const { user } = useAuthenticator((context) => [context.user]);
return (
<div>{user?.username}</div>
);
};
export default App;
Test code here.
import App from 'src/App';
import { render, screen } from '#testing-library/react';
describe('First group',()=>{
test('rendering App component',()=>{
// App includes 'import { useAuthenticator } from '#aws-amplify/ui-react';'
render(<App/>)
screen.debug()
})
})
Error outputs here.
● Test suite failed to run
TypeError: window.URL.createObjectURL is not a function
> 1 | import { useAuthenticator } from '#aws-amplify/ui-react';
| ^
2 |
3 | const App = () => {
4 | const { user } = useAuthenticator((context) => [context.user]);
at define (node_modules/maplibre-gl/dist/maplibre-gl.js:25:43)
at node_modules/maplibre-gl/dist/maplibre-gl.js:35:1
at node_modules/maplibre-gl/dist/maplibre-gl.js:3:81
at Object.<anonymous> (node_modules/maplibre-gl/dist/maplibre-gl.js:6:2)
at Object.<anonymous> (node_modules/#aws-amplify/ui-react/dist/index.js:1:484)
at Object.<anonymous> (src/App.tsx:1:1)
Based on slideshowp2's answer, added setup and config file. But still hits the error. Both are located rootDir.
jest.setup.js
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}
jest.config.js
module.exports = {
setupFilesAfterEnv: ['./jest.setup.js'],
};
UPDATE
This PJ was created by CRA so it required to follow their rule. I finally resolved this by slideshowp2's answer and the correct location to put the pollyfilling code.
src/setupTests.ts
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}
See troubleshooting#jest
As of v2.15.0 of #aws-amplify/ui-react which included the release of Geo components, users of the Jest testing framework may run into the following error when attempting to run tests:
window.URL.createObjectURL is not a function
Please follow the steps below to resolve this issue.
Navigate to or create a Jest setup file for your project.
Add the following code to polyfill the unrecognized function in your Jest setup file:
jest.setup.js:
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = jest.fn();
}
jest.config.js:
module.exports = {
//...
setupFilesAfterEnv: ['./jest.setup.js'],
//...
}
This is a known problem when using the jsdom library (a dependency of Jest) with a package that uses an unrecognized function. See this issue.

React Native Expo - Jest - React Native Firebase - Invariant Violation: Native module cannot be null

I try to run tests with jest but it breaks with an error:
Invariant Violation: Native module cannot be null.
at invariant (node_modules/invariant/invariant.js:40:15)
at RNFBNativeEventEmitter.NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:36:7)
at new RNFBNativeEventEmitter (node_modules/#react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:24:5)
at Object.<anonymous> (node_modules/#react-native-firebase/app/lib/internal/RNFBNativeEventEmitter.js:48:16)
at Object.<anonymous> (node_modules/#react-native-firebase/app/lib/internal/registry/nativeModule.js:21:1)
I use latest versions for RN, Expo, Typescript and others.
My jest config is:
"jest": {
"preset": "jest-expo",
"transformIgnorePatterns": [
"node_modules/(?!(jest-)?react-native|react-native|react-clone-referenced-element|#react-native-community|expo(nent)?|#expo(nent)?/.*|react-navigation|#react-navigation/.*|#unimodules/.*|sentry-expo|native-base|#ui-kitten|#react-native-firebase/auth|#react-native-firebase/app)"
]
},
If I remove #react-native-firebase from transformIgnorePatterns then test fails with error:
import { isAndroid, isBoolean } from '#react-native-firebase/app/lib/common';
^^^^^^
SyntaxError: Cannot use import statement outside a module
1 | import * as React from 'react';
> 2 | import auth, { FirebaseAuthTypes } from '#react-native-firebase/auth';
Try to mock #react-native-firebase/your/needed/module
For example:
jest.mock('#react-native-firebase/app/lib/common', () => ({
isAndroid: jest.fn(() => true),
isBoolean: jest.fn(() => false),
}));

How to fix 'window.URL.createObjectURL is not a function' when testing mapbox-gl in React?

I'm testing React component with Mapbox, material-ui and custom styles. I use Jest + Enzyme for testing.
I have problem: 'window.URL.createObjectURL is not a function'. I read similar questions:
github.com/uber/react-map-gl/issues/210
github.com/mapbox/mapbox-gl-js/issues/3436
github.com/mapbox/mapbox-gl-js-mock
and tried to add something but without success. Please, fix the issue.
CodeSandbox
I had faced exactly same issue with my jest test suite. After some trial and searching, I was able to mock the createObjectURL method.
In jest.stub.js file, I put this config:
if (typeof window.URL.createObjectURL === 'undefined') {
window.URL.createObjectURL = () => {
// Do nothing
// Mock this function for mapbox-gl to work
};
}
Then, in jest.config.js file, I added a reference to the stub file
setupFiles: [
'<rootDir>/tests/jest.stub.js',
],
Note: make sure you get the path right in setupFile defintion.
I had the same issue running tests using the library Plotly.js with React and Jest.
My solution was to add a file src/setupTests.js with a mock for the createObjectURL function window.URL.createObjectURL = function() {};
I also was using React with Mapbox-gl and #Pablo Jurado's solution worked perfectly.
Just pasted window.URL.createObjectURL = function() {};
to src/setupTest.js file
and also modified npm test script to:
"scripts": { "test": "react-scripts test --transformIgnorePatterns \"node_modules/(?!your-module-name)/\"", },
based on
this example
Add package: mapbox-gl-js-mock
add require("mapbox-gl-js-mock"); before jest.mock(
import React from 'react';
import { createShallow } from '#material-ui/core/test-utils';
import App from './App';
require("mapbox-gl-js-mock");
jest.mock('mapbox-gl/dist/mapbox-gl', () => ({
App: () => ({}),
}));
describe('<App />', () => {
let shallow;
beforeEach(() => {
shallow = createShallow({ dive: true });
});
it('renders without crashing', () => {
const wrapper = shallow(<App />);
expect(wrapper.find('.MapBox')).toExist();
});
});

`ReferenceError: TextEncoder is not defined` when running `react-scripts test --env=jsdom`

I'm using a TensorFlow encoder in my application. It works fine in my browser when the application is running but I get issues when testing that it builds:
$ npx react-scripts test --env=jsdom
FAIL src/App.test.js
● Test suite failed to run
ReferenceError: TextEncoder is not defined
16 | import TextField from '#material-ui/core/TextField';
17 | import Typography from '#material-ui/core/Typography';
> 18 | import * as mobilenet from '#tensorflow-models/mobilenet';
| ^
19 | import * as UniversalSentenceEncoder from '#tensorflow-models/universal-sentence-encoder';
20 | import * as tf from '#tensorflow/tfjs';
21 | import axios from 'axios';
at new PlatformBrowser (node_modules/#tensorflow/tfjs-core/src/platforms/platform_browser.ts:26:28)
at Object.<anonymous> (node_modules/#tensorflow/tfjs-core/src/platforms/platform_browser.ts:50:30)
at Object.<anonymous> (node_modules/#tensorflow/tfjs-core/src/index.ts:29:1)
at Object.<anonymous> (node_modules/#tensorflow/tfjs-converter/src/executor/graph_model.ts:18:1)
at Object.<anonymous> (node_modules/#tensorflow/tfjs-converter/src/index.ts:17:1)
at Object.<anonymous> (node_modules/#tensorflow-models/mobilenet/dist/index.js:38:14)
at Object.<anonymous> (src/components/model.js:18:1)
at Object.<anonymous> (src/App.js:8:1)
at Object.<anonymous> (src/App.test.js:3:1)
I'd like to get rid of that error. I've tried using the 'text-encoding' package but I'm not sure how get TextEncoder properly defined before the import happens.
Maybe I can set a different option for --env?
I get the same error without --env=jsdom. I believe I added it after getting similar types of not defined errors and it corrected an issue.
Here is my test:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
So setting --env=node does not work either because: ReferenceError: document is not defined.
jsdom Doesn't seem to have TextEncoder defined in global for the DOM. So you can fill it in with the node.js one.
test/custom-test-env.js:
const Environment = require('jest-environment-jsdom');
/**
* A custom environment to set the TextEncoder that is required by TensorFlow.js.
*/
module.exports = class CustomTestEnvironment extends Environment {
async setup() {
await super.setup();
if (typeof this.global.TextEncoder === 'undefined') {
const { TextEncoder } = require('util');
this.global.TextEncoder = TextEncoder;
}
}
}
npx react-scripts test --env=./test/custom-test-env.js
I am getting same error for my Node.Js project. For testing purpose I used jest there. So following steps are resolved my issue
step-1: on the root folder of your project add a file named as jest.config.js
step-2: Add the following lines in the jest.config.file:
module.exports = {
testEnvironment: "node"
};
Thanks for these answers. A simpler format that seems to work, at least with testEnvironment: 'jsdom' is:
setupFiles: [`<rootDir>/jest-shim.js`],
jest-shim.js:
import { ArrayBuffer, TextDecoder, TextEncoder, Uint8Array } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
global.ArrayBuffer = ArrayBuffer;
global.Uint8Array = Uint8Array;
I faced this problem when using mongodb. I used #Phoenix solution with a little change.
First I used jest-environment-node instead of jest-environment-jsdom:
const NodeEnvironment = require('jest-environment-node');
// A custom environment to set the TextEncoder that is required by mongodb.
module.exports = class CustomTestEnvironment extends NodeEnvironment {
async setup() {
await super.setup();
if (typeof this.global.TextEncoder === 'undefined') {
const { TextEncoder } = require('util');
this.global.TextEncoder = TextEncoder;
}
}
}
Then I added the environment in the jest configs for all tests as Cava said in the comments:
// package.json
{
...
"jest": {
...
"testEnvironment": "<rootDir>/tests/custom-test-env.js"
}
...
}
According to the latest jest v28 (https://jestjs.io/docs/upgrading-to-jest28) and react 18
I had to modify a bit the script
so my preSetup.js
const Environment = require('jest-environment-jsdom-global');
/**
* A custom environment to set the TextEncoder
*/
module.exports = class CustomTestEnvironment extends Environment {
constructor({ globalConfig, projectConfig }, context) {
super({ globalConfig, projectConfig }, context);
if (typeof this.global.TextEncoder === 'undefined') {
const { TextEncoder } = require('util');
this.global.TextEncoder = TextEncoder;
}
}
};
next babel works
● Test suite failed to run
ReferenceError: TextEncoder is not defined
1 | import assert from 'assert'
> 2 | import { fromUrl, parseDomain, ParseResultType } from 'parse-domain'
| ^
3 | import { toUnicode } from 'punycode'
// ...
setupFiles: [`<rootDir>/jest-shim.js`],
testEnvironment: 'jest-environment-jsdom',
// ...
import { TextDecoder, TextEncoder } from 'util'
global.TextEncoder = TextEncoder
global.TextDecoder = TextDecoder
Doesnt work using below config
"testEnvironment": "<rootDir>/tests/custom-test-env.js"
const NodeEnvironment = require('jest-environment-node');
// A custom environment to set the TextEncoder that is required by mongodb.
module.exports = class CustomTestEnvironment extends NodeEnvironment {
async setup() {
await super.setup();
if (typeof this.global.TextEncoder === 'undefined') {
const { TextEncoder } = require('util');
this.global.TextEncoder = TextEncoder;
}
}
}
using "jest": "^28.0.3",
Although all other answers seems to work fine, but I couldn't use any of them in my react-scripts app.
to fix the problem, I used this approach and it solved my issue.
This approach doesn't require adding a test environment as jest config.
Add this to src/setupTests.ts
import '#testing-library/jest-dom';
import { TextEncoder } from 'util';
global.TextEncoder = TextEncoder;

Resources