The development environment uses next.js 13.
After updating the query-string library to 8.1, test:ci now fails.
It fails at the following point.
before "query-string": "^7.1.0",
after "query-string": "^8.1.0",
error
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as queryString from './base.js';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Changed part.
before
import { stringifyUrl } from 'query-string';
.
. omission
.
stringifyUrl({url})
after
import queryString from 'query-string';
.
. omission
.
queryString.stringifyUrl({ url })
I am very troubled.
If anyone knows how to solve this problem, please let me know.
added
module.exports = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
collectCoverageFrom: ['src/**/*.{js,jsx,ts,tsx}', '!**/*.d.ts'],
moduleDirectories: ['node_modules', 'src'],
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>/src/__mocks__/styleMock.ts',
// Handle image imports
// https://jestjs.io/docs/webpack#handling-static-assets
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/src/__mocks__/fileMock.ts`,
// Handle ESM packages
'^react-markdown$': '<rootDir>/src/__mocks__/react-markdown.tsx',
},
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
testEnvironment: 'jest-environment-jsdom',
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)$',
],
};
The issue is query-string version 8 introduced a breaking to consuming applications because their dependencies upgraded to ESM. See their release notes here:
v8.0.0
Breaking
Require Node.js 14
This package is now pure ESM. Please read this.
Add "module": "node16", "moduleResolution": "node16" to your
tsconfig.json.
(Example)
And more!!!
It appears Jest in trying to use import but it's not configured to do so. Jest also provides some guidance for how to deal with this: https://jestjs.io/docs/ecmascript-modules
Since you're using Next.js, those steps don't really apply.
I'm reproducing and testing in a sandbox... Will update shorty.
For React apps:
Try setting "type": "module" inside package.json.
You should also update your package.json test script to:
"test": "node --experimental-vm-modules ./node_modules/.bin/jest"
Now inside jest.config.js you'll want to export transform: {}:
export default {
transform: {}
}
After all those steps, you should no longer have this issue.
Related
I'm getting an error when trying to run my test file (I'm using react typescript)
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
export {uriTransformer} from './lib/uri-transformer.js'
^^^^^^
SyntaxError: Unexpected token 'export'
5 | const Markdown = ({ text, classStyle }: ITextMedia) => (
6 | <div className={`${classes.mediaParagraph} ${classStyle ?? ''}`}>
> 7 | <ReactMarkdown>{text}</ReactMarkdown>
| ^
8 | </div>
9 | );
10 | export default Markdown;
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (components/media/markdown/index.tsx:7:45)
I already tried adding the React markdown to the transform ignore patterns, but it still doesn't work
here's my jest.config
{
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'next/router': '<rootDir>/__mocks__/next/router.js',
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
},
transform: {
'^.+\\.(js|jsx)$': 'babel-jest'
},
transformIgnorePatterns: [
'node_modules/(?!react-markdown/)'
]
}
my babel config:
{
"presets": [
"next/babel",
"#babel/preset-env"
],
"plugins": []
}
I'm new to jest, so I'm not sure if I'm doing something wrong
In the jest.config file, you need to add the following to the moduleNameMapper attribute:
"react-markdown": "<rootDir>/node_modules/react-markdown/react-markdown.min.js"
So effectively, your moduleNameMapper should really look like this:
...
moduleNameMapper: {
'next/router': '<rootDir>/__mocks__/next/router.js',
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': '<rootDir>/__mocks__/file-mock.js',
'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
},
...
Good luck!
I am trying to set up Storybook in a project. My project is runing on react#^16, and I'm using typescript, with a custom babel and webpack setup for development and build. To set up storybook, I did
npx sb init
This installs everything needed. It puts a .storybook folder in the root folder, and a stories folder in my src folder with some prefab components and stories in tsx format (which is what I want):
The .storybook/main.js file seems fine:
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
]
}
And the average .stories.js file automatically installed by npx sb init also seems fine:
import React from 'react';
// also exported from '#storybook/react' if you can deal with breaking changes in 6.1
import { Story, Meta } from '#storybook/react/types-6-0';
import { Header, HeaderProps } from './Header';
export default {
title: 'Example/Header',
component: Header,
} as Meta;
const Template: Story<HeaderProps> = (args) => <Header {...args} />;
export const LoggedIn = Template.bind({});
LoggedIn.args = {
user: {},
};
export const LoggedOut = Template.bind({});
LoggedOut.args = {};
But when I run npm run storybook, the storybook landing page has no stories. Even though it had installed some default stories to start playing with. It says:
Oh no! Your Storybook is empty. Possible reasons why:
The glob specified in main.js isn't correct.
No stories are defined in your story files.
As requested, here is a link to the repo so you can dig a bit deeper into the structure, weback config, etc. Note I have not committed the npx sb init changes yet, so you won't see the files there, only my starting point just before running the sb init.
I haven't had any issues getting npx sb init to work with a standard create-react-app, but with my custom webpack build and typescript, its just empty. What's going wrong?
Edit: Additional detail
I realize that just running npx sb init, then npm run storybook throws this error:
ERROR in ./.storybook/preview.js-generated-config-entry.js
Module not found: Error: Can't resolve 'core-js/modules/es.array.filter'
Based on this thread, installing core-js#3 solves the problem and storybook runs, though with no stories.
It seems like the babel plugin transform-es2015-modules-amd doesn't fit right with storybook since sb still uses your babel configuration.
You might need to remove it then it would work:
{
"plugins": [
// "transform-es2015-modules-amd", // Remove this plugin
]
}
If you want to have a special babel configuration for storybook, place it .storybook/.babelrc so the configuration would be simple like this:
.storybook/.babelrc:
{
"presets": ["#babel/preset-env", "#babel/preset-react", "#babel/preset-typescript"]
}
NOTE: You might miss to forget install #babel/preset-typescript to help you transform your typescript code.
Maybe you have problems with the stories path, try to save only "../src/**/*.stories.js" in your config to see if its the reason
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
]
In case of dealing with arcgis-js-api in sb, you have to declare #arcgis/webpack-plugin in storybook's webpack configuration by adding to its config.
Here are a few steps you have to do:
Add webpackFinal property in .storybook/main.js with following content:
const ArcGISPlugin = require('#arcgis/webpack-plugin');
module.exports = {
// ...
webpackFinal: (config) => {
// Add your plugin
config.plugins.push(
new ArcGISPlugin(),
);
// Since this package has used some node's API so you might have to stop using it as client side
config.node = {
...config.node,
process: false,
fs: "empty"
};
return config;
}
};
One more thing to be aware of, some components are importing scss files, so you might need to support it by adding a scss addon '#storybook/preset-scss'
// Install
npm i -D #storybook/preset-scss css-loader sass-loader style-loader
// Add to your current addons
{
addons: ['#storybook/addon-links', '#storybook/addon-essentials', '#storybook/preset-scss'],
}
Like a tmhao2005 say. Storybook still uses your babel configuration. And this is the intended behavior. This thread at github also describes how the fix similar issue.
Updated your config .storybook/main.js.
If you use .babelrc:
babel: async options => ({ ...options, babelrc: false })
Or .babel.config.js:
babel: async options => ({ ...options, configFile: false })
I'm currently importing a module using file loader in one of my files in a react app (CRA):
"file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js"
When running Jest, it throws this error:
Cannot find module 'file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js'
I've attempted different configs in package.json for Jest, by setting either modulePathIgnorePatterns and moduleNameMapper, but neither config setting works:
"modulePathIgnorePatterns": [
"file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js"
]
"moduleNameMapper": {
"file-loader?name=scripts/[name].[hash].js!jsstore/dist/jsstore.worker.min.js": "<rootDir>/node_modules/jsstore/dist/jsstore.worker.min.js"
}
You can map this import to a file that will return a string which what file-loader returns;
moduleNameMapper: {
"^file\-loader":"<rootDir>/__mocks__/fileMock.js",
}
// __mocks__/fileMock.js
module.exports = 'file-path-mock';
I have the following line that executes correctly in browser
eval(Babel.transform(template, { presets: ['react'] }).code);
but when I run jest tests I am getting ReferenceError: React is not defined
What am I missing?
More info:
in the test file I have the following:
const wrapper = shallow(<MyComponent/>);
const instance = wrapper.instance();
instance.componentFunction(...)
and then the componentFunction has the eval(Babel.transform(template, { presets: ['react'] }).code); line where template is something it gets from the test file and can be something like <span>...</span>
Please let me know if more details are needed
#babel/preset already has support for what you need. According to the react 17 documentation I only had to set the runtime to automatic in my babel.config.json.
{
"presets": [
["#babel/preset-react", {
"runtime": "automatic"
}]
]
}
If you are using #babel/plugin-transform-react-jsx the config should be
{
"plugins": [
["#babel/plugin-transform-react-jsx", {
"runtime": "automatic"
}]
]
}
The latter is usually not needed since #babel/preset-react includes #babel/plugin-transform-react-jsx.
Why you shouldn't use import React from 'react';
The documentation states:
There are some performance improvements and simplifications that React.createElement does not allow.
There is also a technical RFC that explains how the new transformation works.
If you want to upgrade. React also provides an automated script that removes unnecessarry imports from your code.
If you are using JSX in your jest test files, you will need to add the following import line to the top of the file:
import React from 'react';
The reason for this is that Babel transforms the JSX syntax into a series of React.createElement() calls, and if you fail to import React, those will fail.
The best solution for Next.js (where jsx: 'preserve' specifically is:
Configuring your babel config in the way that next already does: (no need to install another babel plugin):
babel.config.js:
module.exports = {
presets: ['next/babel']
};
Alternatively, if anyone experienced this bug had the problem wherein import React from 'react' is not necessary, because it is already included globally and doesn't need to be included in every file, then this solution may work for you.
I simply configured React to be globally defined in jest.
My jest.config.js:
module.exports = {
moduleDirectories: ['./node_modules', 'src'],
// other important stuff
setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts']
}
import '#testing-library/jest-dom';
import React from 'react';
global.React = React; // this also works for other globally available libraries
Now I don't need to worry about each file importing React (even though eslint knows that's unnecessary with Next.js)
This happened to me after react-native and jest and other node_modules related to unit test were upgraded.
Here is my working config:
jest.config.js
module.exports = {
preset: 'react-native',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
moduleDirectories: ['./node_modules', 'src'],
cacheDirectory: '.jest/cache',
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!#react-native|react-native)',
],
moduleNameMapper: {
'^[./a-zA-Z0-9$_-]+\\.svg$': '<rootDir>/tests/SvgStub.js'
},
setupFiles: ['./jest-setup.js'],
modulePathIgnorePatterns: ['<rootDir>/packages/'],
watchPathIgnorePatterns: ['<rootDir>/node_modules'],
}
For setup file I had to use project specific one ./jest-setup.js but for a general use './node_modules/react-native-gesture-handler/jestSetup.js' should work too.
babel.config
{
presets: ['module:metro-react-native-babel-preset'],
plugins: [
'react-native-reanimated/plugin'
]
};
Sources: https://github.com/facebook/jest/issues/11591#issuecomment-899508417
More info about the dependencies here: https://stackoverflow.com/a/74278326/1979861
If you are storing test data in separate test data files that contain JSX, you will also need to import react, as your file contains JSX and so results in a ReferenceError: React is not defined in jest tests error.
const testData = {
"userName": "Jane Bloggs",
"userId": 101,
"userDetailsLink": Jane Bloggs
};
importing react, as below, resolves the error.
import React from "react";
const testData = {
"userName": "Jane Bloggs",
"userId": 101,
"userDetailsLink": Jane Bloggs
};
I use webpack to develop a React component. Here is a simple version of it:
'use strict';
require('./MyComponent.less');
var React = require('react');
var MyComponent = React.createClass({
render() {
return (
<div className="my-component">
Hello World
</div>
);
}
});
module.exports = MyComponent;
Now, I would like to test this component using jest. Here is the relevant bit from my package.json:
"scripts": {
"test": "jest"
},
"jest": {
"rootDir": ".",
"testDirectoryName": "tests",
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"unmockedModulePathPatterns": [
"react"
]
}
When running npm test, I get the following error:
SyntaxError: /Users/mishamoroshko/react-component/src/tests/MyComponent.js: /Users/mishamoroshko/react-component/src/MyComponent.js: /Users/mishamoroshko/react-component/src/MyComponent.less: Unexpected token ILLEGAL
Looks like webpack needs to process require('./MyComponent.less') before jest can run the test.
I wonder if I need to use something like jest-webpack. If yes, is there a way to specify multiple scriptPreprocessors? (note that I already use babel-jest)
The cleanest solution I found for ignoring a required module is to use the moduleNameMapper config (works on the latest version 0.9.2)
The documentation is hard to follow. I hope the following will help.
Add moduleNameMapper key to your packages.json config. The key for an item should be a regex of the required string. Example with '.less' files:
"moduleNameMapper": { "^.*[.](less|LESS)$": "EmptyModule" },
Add a EmptyModule.js to your root folder:
/**
* #providesModule EmptyModule
*/
module.exports = '';
The comment is important since the moduleNameMapper use EmptyModule as alias to this module (read more about providesModule).
Now each require reference that matches the regex will be replaced with an empty string.
If you use the moduleFileExtensions configuration with a 'js' file, then make sure you also add the EmptyModule to your 'unmockedModulePathPatterns'.
Here is the jest configuration I ended up with:
"jest": {
"scriptPreprocessor": "<rootDir>/node_modules/babel-jest",
"moduleFileExtensions": ["js", "json","jsx" ],
"moduleNameMapper": {
"^.*[.](jpg|JPG|gif|GIF|png|PNG|less|LESS|css|CSS)$": "EmptyModule"
},
"preprocessorIgnorePatterns": [ "/node_modules/" ],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/EmptyModule.js"
]
}
I ended up with the following hack:
// package.json
"jest": {
"scriptPreprocessor": "<rootDir>/jest-script-preprocessor",
...
}
// jest-script-preprocessor.js
var babelJest = require("babel-jest");
module.exports = {
process: function(src, filename) {
return babelJest.process(src, filename)
.replace(/^require.*\.less.*;$/gm, '');
}
};
But, I'm still wondering what is the right solution to this problem.
I just found that it's even simpler with Jest's moduleNameMapper configuration.
// package.json
"jest": {
"moduleNameMapper": {
"^.+\\.scss$": "<rootDir>/scripts/mocks/style-mock.js"
}
}
// style-mock.js
module.exports = {};
More detail at Jest's tutorial page.
I recently released Jestpack which might help. It first builds your test files with Webpack so any custom module resolution/loaders/plugins etc. just work and you end up with JavaScript. It then provides a custom module loader for Jest which understands the Webpack module runtime.
From Jest docs:
// in terminal, add new dependency: identity-obj-proxy
npm install --save-dev identity-obj-proxy
// package.json (for CSS Modules)
{
"jest": {
"moduleNameMapper": {
"\\.(css|less)$": "identity-obj-proxy"
}
}
}
The snippet above will route all .less files to the new dependency identity-obj-proxy, which will return a string with the classname when invoked, e.g. 'styleName' for styles.styleName.
I think a less hacky solution would be to wrap your preprocessor in a conditional on the filename matching a javascript file:
if (filename.match(/\.jsx?$/)) {
return babelJest.process(src, filename);
} else {
return '';
}
This works even if you don't explicitly set the extension in the require line and doesn't require a regex substitution on the source.
I have experienced similar issue with such pattern
import React, { PropTypes, Component } from 'react';
import styles from './ContactPage.css';
import withStyles from '../../decorators/withStyles';
#withStyles(styles)
class ContactPage extends Component {
see example at https://github.com/kriasoft/react-starter-kit/blob/9204f2661ebee15dcb0b2feed4ae1d2137a8d213/src/components/ContactPage/ContactPage.js#L4-L7
For running Jest I has 2 problems:
import of .css
applying decorator #withStyles (TypeError: <...> (0 , _appDecoratorsWithStyles2.default)(...) is not a function)
First one was solved by mocking .css itself in script preprocessor.
Second one was solved by excluding decorators from automocking using unmockedModulePathPatterns
module.exports = {
process: function (src, filename) {
...
if (filename.match(/\.css$/)) src = '';
...
babel.transform(src, ...
}
}
example based on https://github.com/babel/babel-jest/blob/77a24a71ae2291af64f51a237b2a9146fa38b136/index.js
Note also: when you working with jest preprocessor you should clean cache:
$ rm node_modules/jest-cli/.haste_cache -r
Taking inspiration from Misha's response, I created an NPM package that solves this problem while also handling a few more scenarios I came across:
webpack-babel-jest
Hopefully this can save the next person a few hours.
If you're using babel, you can strip unwanted imports during the babel transform using something like https://github.com/Shyp/babel-plugin-import-noop and configuring your .babelrc test env to use the plugin, like so:
{
"env": {
"development": {
...
},
"test": {
"presets": [ ... ],
"plugins": [
["import-noop", {
"extensions": ["scss", "css"]
}]
]
}
}
}
We had a similar problem with CSS files. As you mentioned before jest-webpack solves this problem fine. You won't have to mock or use any module mappers either. For us we replaced our npm test command from jest to jest-webpack and it just worked.
Webpack is a great tool, but I don't need to test it's behavior with my Jest unit tests, and adding a webpack build prior to running unit tests is only going to slow down the process. The text-book answer is to mock non-code dependencies using the "moduleNameMapper" option
https://facebook.github.io/jest/docs/webpack.html#handling-static-assets