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

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)/\"",

Related

How to fix ReferenceError: TextEncoder is not defined in jest test of Next.js project?

I have a unit test that is checking to see if a particular item is rendered on the page. This unit test fails and I get the following error:
Test suite failed to run
ReferenceError: TextEncoder is not defined
6 | import { unformatPhoneNumber } from '../../../utils/formatter';
7 | import ReactHtmlParser from 'react-html-parser';
> 8 | import DOMPurify from 'isomorphic-dompurify';
Based on the other stackoverflow questions on this subject, I added a jest.config.js file and a jest.setup.js file in the root of my project.
This is what I have in my jest.config.js, which I copied from the Next.js example repo here,
https://github.com/vercel/next.js/tree/canary/examples/with-jest-babel
// You can learn more about each option below in the Jest docs: https://jestjs.io/docs/configuration.
module.exports = {
collectCoverageFrom: ['**/*.{js,jsx,ts,tsx}', '!**/*.d.ts', '!**/node_modules/**'],
moduleNameMapper: {
// Handle CSS imports (with CSS modules)
// https://jestjs.io/docs/webpack#mocking-css-modules
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
// Handle CSS imports (without CSS modules)
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
// Handle image imports
// https://jestjs.io/docs/webpack#handling-static-assets
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,
// Handle module aliases
'^#/components/(.*)$': '<rootDir>/components/$1',
'^#/pages/(.*)$': '<rootDir>/pages/$1',
},
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
transform: {
// Use babel-jest to transpile tests with the next/babel preset
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: ['/node_modules/', '^.+\\.module\\.(css|sass|scss)$'],
testEnvironment: 'jest-environment-jsdom',
};
This is what I have in the jest.setup.js,
// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.js`
// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '#testing-library/jest-dom/extend-expect';
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
After adding this, I am still getting the same error. I am using node v16.18.0.
This is a Nextjs, Typescript, React app. I also have a jest-config.d.ts file with the following in it:
declare const root: any;
export { root as rootDir };
export declare const setupFilesAfterEnv: string['<rootDir>/jest.setup.js'];
export declare const testMatch: string[];
export declare const testPathIgnorePatterns: string[];
export declare const coveragePathIgnorePatterns: string[];
export declare const coverageDirectory: string;
//# sourceMappingURL=jest-config.d.ts.map
I don't know if I need to add anything into this file.

Jest can't find .env.local for MONGO_URI

I have a NextJS app using a MongoDB. I just added Jest for testing. When I run the first test I get the following error:
Please define the MONGODB_URI environment variable inside .env.local
4 |
5 | if (!MONGODB_URI) {
> 6 | throw new Error('Please define the MONGODB_URI environment variable inside .env.local');
| ^
7 | }
I do have a file .env.local that has a MONGODB_URI and it works when I run my app locally and and on prod.
This is the test:
import React from 'react';
import ReactDom from 'react-dom';
import Home from '../../pages/index';
import { configure, shallow } from 'enzyme';
import Adapter from '#wojtekmaj/enzyme-adapter-react-17';
configure({ adapter: new Adapter() });
describe('<Home />', () => {
it('should render Home', () => {
const wrapper = shallow(<Home />);
console.log('wrapper :', wrapper.debug());
});
});
My jest.config.js:
module.exports = {
clearMocks: true,
coverageDirectory: 'coverage',
moduleNameMapper: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
'\\.(css|less)$': 'identity-obj-proxy'
},
preset: '#shelf/jest-mongodb'
};
What am I missing here?
The .env.local is not loaded in the test environment, as you expect tests to produce the same results for everyone.
But you can still use environment variables for tests.
1. Option
You can use a env.test file and add the following to a globalSetup.js file
...
import { loadEnvConfig } from '#next/env'
export default async () => {
const projectDir = process.cwd()
loadEnvConfig(projectDir)
}
...
Make sure to setup the globalSetup.js file in the jest.config.js file:
...
globalSetup: ['<rootDir>/test/globalSetup.js'] // path to file
...
When you run your tests there should be a log in the console:
Loaded env from C:\Users\XXX\XXX\XXX\nextjs\.env.test
More information here: Next.js Environment Variables Documentation
2. Option
You can use the dotenv package for the test env with the env.local file.
Add this in your jest-setup.js file:
import dotenv from 'dotenv'
dotenv.config({ path: '.env.local' })
in nextJS, I use .env.test for test environment.
you will have to pass setupFiles option in the jest.config.js
module.exports = {
setupFiles: ['env.local.config file'],
}
to use MONGODB_URI in the tests

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();
});
});

make sure to include the file in Jest's transformIgnorePatterns as wel

I'm trying to make jest/enzyme tests in react
I have this test:
import React from 'react';
import { shallow } from 'enzyme';
import { mount } from 'enzyme'
import WorkOutForm from './workOutForm';
describe('WorkOutForm', () => {
it('should start a new workoutForm with empty state', () => {
const component = mount(<WorkOutForm/>)
expect(component).toMatchSnapshot();
});
})
but when i do a npm run test i receive:
src/workout/workOut.test.js ● Test suite failed to run
babel-jest: Babel ignores src/workout/workOutForm.jsx - make sure to include the file in Jest's transformIgnorePatterns as well.
I try to add this file in the package.json:
"jest": {
"transformIgnorePatterns": [
"src/workout/workOutForm.jsx"
]
}
but i'm receiving the same error.
where i have to put this?
where i have to put this?
You should not ignore jsx source files. What you need to do is convert your jsx to js using babel.
You need to use babel-preset-react. This will automatically add #babel/plugin-transform-react-jsx for the transformation.
Then put this in your .babelrc
{
"presets": ["#babel/preset-react"]
}
I have already this error and i fixed changing the code from:
"ignore": [
"./test",
"./src/assets",
"./src/stories",
"./src/.storybook"
]
To this:
"ignore": [
"./src/assets",
"./src/stories",
"./src/.storybook"
]
I remove my test folder from the .babelrc ignore prop and its works for me!

Using React stroybook as Jest test

I have a React storybook and what to use it as my test cases
I have a "loader.js" that import all the stories
import sourceBasic from 'raw-loader!./Basics/foo.js?sourceMap';
import Basic from './Basics/foo';
const tree = {
Basics:[
{
title:'Creating and applying a style',
source:sourceBasic, element:Basic
},
{ .... }
],
[ .... ],
....
}
export default tree
I use the raw-loader and sourceMap to show the source with the element in storybook
This works great.
My problem is when I try to import with Jest
FAIL ./index.test.js
● Test suite failed to run
Cannot find module 'raw-loader!./Basics/foo.js?sourceMap' from 'load.js'
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
at Object.<anonymous> (example/stories/load.js:2:34)
The test file
import React from 'react';
import renderer from 'react-test-renderer';
import load from './example/stories/load'
for(const groupName in load ){
const groupArray = load[groupName];
describe(groupName, () => {
for(const item of groupArray ){
test(item.title, () => {
const elem = renderer.create(item.element);
expect(elem.toJSON()).toMatchSnapshot();
}) // END test
} // END for
}) // END describe
} // END for
Thanks for your help
UPDATE
The update and working stroybook as test is implemented on the project react-outline
You can clone it(react-outline), npm install and then npm test to see it in action.
Here is the output on travis :)
If you don't care about the raw-source and want to mock it. You can use the moduleNameMapper under your Jest setting within your package.json.
This will let you intercept all require/import based on a regex match.
Add to your package.json:
...
"dependencies": {
...
},
...
"jest": {
"globals": {
"__TEST__": true
},
"moduleNameMapper": {
"\\.(css|jpg|png)$": "<rootDir>/empty-module.js",
"^raw-loader": "<rootDir>/empty-module.js"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"verbose": true
}
}

Resources