Trying to test using jest but running into issues - reactjs

Im trying to test a component using jest. The component imports spacetime npm module, which uses es-modules on main
https://www.npmjs.com/package/spacetime
I'm running into the following issues:
● 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:
/Users/wscott/dev/pm/client/node_modules/spacetime/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Spacetime from './spacetime.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
6 | import search from '../../assets/images/search.svg';
7 | import Dropdown from 'react-bootstrap/Dropdown';
> 8 | import spacetime from "spacetime";
| ^
9 | import languages from "../../libraries/languages/language-list";
10 | import { Rating } from 'react-simple-star-rating';
11 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/Mentor/MentorList.js:8:1)
Here's my jest.config.js file
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(css|styl|less|sass|scss)$": "jest-transform-css"
},
"moduleNameMapper": {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/src//__mocks__/fileMock.js"
},
"setupFiles":["./src/browserMocks.js"],
"globals": {
"window": {
location: {
href: ""
},
localStorage: {
getItem: () => {
}
}
},
"localStorage": {
getItem: () => {
}
}
}
};
Here's my babel.config.js file:
module.exports = {
presets:[
"#babel/preset-env",
"#babel/preset-react"
],
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Can someone help?

Downgrading to 6.12.3 fixes the issue with jest. The issue is space time use es-module imports which jest doesn't support but downgrading should work

Try to set the transformIgnorePatterns property to let jest transform the file before tests:
transformIgnorePatterns: [
'node_modules/(?!(spacetime)/)',
],
This way you are telling to skip transformation for all your node_modules except spacetime, which will be transformed by babel-jest as is set in you configuration.

Related

How to setup jest with node_modules that use es6

I have a very simple test:
describe('sanity', () => {
it('sanity', () => {
expect(true).toBeTruthy()
})
})
And I'm receiving the following error:
FAIL spec/javascript/sanity_test.js
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
/Users/piousbox/projects/ruby/<project>/node_modules/#atlaskit/tooltip/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { default } from './components/Tooltip';
^^^^^^
SyntaxError: Unexpected token export
3 | import update from "immutability-helper";
4 | import {components} from "react-select-2";
> 5 | import Tooltip from "#atlaskit/tooltip";
| ^
6 | const isEqual = require("react-fast-compare");
7 | import _, {replace} from "lodash";
8 | import { get } from "$shared/request";
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (app/javascript/customer2/components/fob/fob_utils.js:5:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.593s
I have this .babelrc:
{
"presets": ["#babel/react", "#babel/env"]
}
How do I make the trivial test pass?
Matt's answer is accepted b/c it is insightful. The change that did it for me was adding in package.json:
"jest": {
...
"transformIgnorePatterns": [
"node_modules/(?!#atlaskit)"
],
You can add support for multiple packages at once by separating them with a |
"jest": {
...
"transformIgnorePatterns": [
"node_modules/(?!module1|module2|etc)"
],
Two ways you can pass this test:
Option 1.) Setup your babel configuration to handle ES6 imports by add a testing env option (the testing environment flag will be defined in your package.json scripts, for example: "test": "NODE_ENV=testing jest" or "test": "BABEL_ENV=testing jest")...
babel.config.js
module.exports = api => {
api.cache(true);
return {
presets: ["#babel/preset-env", "#babel/preset-react"],
plugins: [
"#babel/plugin-transform-runtime",
["#babel/plugin-proposal-class-properties", { loose: true }],
],
env: {
testing: {
presets: [
[ "#babel/preset-env", { targets: { node: "current" }}],
],
},
},
};
};
Option 2.) Transpile the ES6 module into ES5 syntax in your webpack.config.js configuration:
webpack.config.js
const { NODE_ENV } = process.env
const inDevelopment = NODE_ENV === "development";
module.exports = {
...
module: {
rules: [
...
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: !inDevelopment ? /node_modules\/(?!(#atlaskit\/tooltip))/ : /(node_modules)/,
options: {
cacheDirectory: inDevelopment,
cacheCompression: false,
},
},
...
],
}
...
}
The major difference between the two options is that the first option will only work in a testing environment. If you try to use it in a development/production environment, it may impact other 3rd party packages and cause compilation errors. Therefore, if you plan on moving this into a production environment that supports IE11 and below, then the second option is recommended. HOWEVER, keep in mind that this will transpile the package every time a production build is created and/or a test suite is run. Therefore, if you're working on a very large project (or transpiling multiple ES6 packages), it can be quite resource heavy. Therefore, I'd recommend compiling the 3rd party package(s) from ES6 to ES5 and installing it/them locally or privately (via an NPM package).
Working example (this example includes the second option):
https://github.com/mattcarlotta/transpile-es6-module
To install:
cd ~/Desktop && git clone git#github.com:mattcarlotta/transpile-es6-module.git
cd transpile-es6-module
yarn install
yarn dev to run the demo
yarn test to run test suites

getting jest to work with babel / laravel-mix

I'm using jest and testing-library/react for tests of my ReactJS components in a Laravel app.
My tests break because the component to to test isn't recognised by jest even after importing it into the test. I have the following settings in jest.config.js
module.exports = {
testRegex: 'resources/js/tests/.*.test.js$',
roots: ["<rootDir>/resources/js/"],
moduleDirectories: ["resources/js/components", "resources/js/containers", "resources/js/views", "node_modules"]
}
And in the package.json file
"test": "cross-env NODE_ENV=test jest",
Here's a simple test that fails due to error
import React from "react";
import { render, fireEvent, waitForElement } from "#testing-library/react";
import "#testing-library/jest-dom/extend-expect";
import axiosMock from "axios";
// the component to test
import BlogEditor from "../../components/BlogEditor/BlogEditor";
jest.mock("axios");
test("Blog Editor recieves props and renders", () => {
const { getByTestId } = render(
<BlogEditor
tags={[{ id: 1, name: "A tag"}]}
suggestions={[{id: 2, name: "A Suggestion"}]}
/>
);
});
The error I get is rather cryptic
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
SyntaxError: /Users/anadi/Code/adminpanel/resources/js/tests/BlogEditor/BlogEditor.test.js: Unexpected token (16:8)
14 | test("Blog Editor recived props and renders element", () => {
15 | const { getByTestId } = render(
> 16 | <BlogEditor
| ^
17 | tags={[{ id: 1, name: "A tag"}]}
18 | suggestions={[{id: 2, name: "A Suggestion"}]}
19 | />
at Parser.raise (node_modules/#babel/parser/src/parser/location.js:41:63)
at Parser.unexpected (node_modules/#babel/parser/src/parser/util.js:150:16)
at Parser.parseExprAtom (node_modules/#babel/parser/src/parser/expression.js:1123:20)
at Parser.parseExprSubscripts (node_modules/#babel/parser/src/parser/expression.js:529:23)
at Parser.parseMaybeUnary (node_modules/#babel/parser/src/parser/expression.js:509:21)
at Parser.parseExprOps (node_modules/#babel/parser/src/parser/expression.js:279:23)
at Parser.parseMaybeConditional (node_modules/#babel/parser/src/parser/expression.js:234:23)
at Parser.parseMaybeAssign (node_modules/#babel/parser/src/parser/expression.js:185:21)
at Parser.parseExprListItem (node_modules/#babel/parser/src/parser/expression.js:2077:18)
at Parser.parseCallExpressionArguments (node_modules/#babel/parser/src/parser/expression.js:817:14)
The problem was with my babel and jest configurations, moved jest configuration to package.json (I have no clue why this actually helped) but it did
"jest": {
"verbose": true,
"clearMocks": true,
"collectCoverage": true,
"testRegex" : "resources/js/tests/.*.test.js$",
"roots": ["<rootDir>/resources/js/"],
"moduleDirectories": ["resources/js/components", "resources/js/containers", "resources/js/views", "node_modules"],
"transform": {
"^.+\\.js$": "babel-jest"
},
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/resources/js/__mocks__/fileMock.js",
"\\.(css|scss)$": "<rootDir>/resources/js/__mocks__/styleMock.js"
}
and updated the babel configuration too
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-syntax-dynamic-import"
]
}

Jest SyntaxError: Unexpected token <

I'm want to test a component in a React app using Jest Enzyme with TypeScript. I follow the instructions on the Jest site, but for some reason I get:
SyntaxError: Unexpected token <
I can test test some functions. There isn't any problem with that, but when I use a component, I get an error.
This is the Jest configuration in file package.json:
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testMatch": ["**/__tests__/*.(ts|tsx)"],
"snapshotSerializers": ["enzyme-to-json/serializer"],
"setupFilesAfterEnv": ["<rootDir>/src/setupEnzyme.ts"],
"unmockedModulePathPatterns": ["node_modules/react/", "node_modules/enzyme/"]
}
Enzyme configuration
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
export default class TesComponent extends Component {
render(){
return (
<div>test</div>
)
}
}
import { shallow } from 'enzyme'
import TestCompoenent from '../TestComponent'
test('component testing', () => {
const component = shallow(<TestCompoenent />)
expect(component.contains(<div>test</div>)).toBeTruthy()
})
This is the error:
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g., it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• 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/en/configuration.html
Details:
/home/user/Documents/local-platform/frontend/src/pages/__tests__/settigs.test.tsx:9
var component = enzyme_1.shallow(<TestComponent_1.default />);
^
SyntaxError: Unexpected token <
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:471:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:513:25)
I expect for the tests to pass, because Test Component does include <div>test</div>.
Try changing tsconfig.json
"jsx": "preserve" -> "jsx": "react"
It seems that your configuration does not process the TypeScript file (.tsx) properly.
Here is part of my working configuration:
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest",
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"json"
],
"setupTestFrameworkScriptFile": "<rootDir>/src/setupSpecs.ts"
}
I have used setupTestFrameworkScriptFile instead of setupFilesAfterEnv.

Importing images breaks jest test

In React components importing assets
(ex, import logo from "../../../assets/img/logo.png)
gives such error
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){�PNG
SyntaxError: Invalid or unexpected token
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
my jest config is
"jest": {
"testRegex": ".*\\.spec\\.js$",
"moduleFileExtensions": [
"js",
"jsx",
"json"
],
"moduleDirectories": [
"node_modules",
"src",
"assets"
],
"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|scss)$": "<rootDir>/__mocks__/styleMock.js"
},
"verbose": true,
"bail": true
}
what am i missing?
When you import image files, Jest tries to interpret the binary codes of the images as .js, hence runs into errors.
The only way out is to mock a default response anytime jest sees an image import!
How do we do this?
first you tell Jest to run the mock file each time an image import is encountered. you do this by adding the key below to your package.json file
"jest": {
"moduleNameMapper": {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/mocks/fileMock.js",
"\\.(css|less)$": "<rootDir>/mocks/fileMock.js"
}
}
Note: if you already have the "Jest" key, just add the "moduleNameMapper" child in it
lastly, create a mocks folder in your root and create fileMock.js file inside it. populate the file with the snippet below
module.exports = '';
Note: If you are using es6 you can use export default ''; to avoid an Eslint flag
when you are done with the above steps, you can restart the test and you are good to go.
Note. remember to add the varying extensions of your image files in the moduleNameMapper so that they can be mocked.
I hope I have been able to help. #cheers!
For anyone looking into this problem. You have to do install npm install --save-dev identity-obj-proxy to get the necessary dependencies.
"jest": {
"moduleNameMapper": {
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "identity-obj-proxy"
}
}
I had the same problem and I solved it as follows:
npm install -D jest-transform-stub
Then, in package.json, I added the following transformation:
"jest": {
...
"transform": {
...
".+\\.(css|scss|png|jpg|svg)$": "jest-transform-stub"
I had this same issue! I'm not sure if it's the same case as in the original question, but for me jest was still somehow trying to load the images as JS and trying to parse them while I had the files matching image extensions mapped to a mock in moduleNameMapper. My file also included some code to map the # character to the root src directory, since I had webpack and this was configured as a webpack alias in the project (and in TS). The full moduleNameMapper entry in jest.config.js looked like this for me:
moduleNameMapper: {
'^#$': '<rootDir>/src',
'^#/(.*)':
'<rootDir>/src/$1',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
// '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
'.*\\.(css|less)$': 'identity-obj-proxy',
}
For me it turned out that when I was importing the images in my components, the path was something like: '#/assets/someImage.jpg'. However, it seems this would match the first regex first, the one covering the # alias: ^#/(.*). Thus, it was being mapped to <rootDir>/src/$1 instead of the <rootDir>/__mocks__/fileMock.js.
I fixed it by making the alias only match non-images:
moduleNameMapper: {
'^#$': '<rootDir>/src',
'^#/(.*)\\.(?!jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/src/$1',
'.*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/__mocks__/fileMock.js',
// '\\.(css|less)$': '<rootDir>/__mocks__/styleMock.js',
'.*\\.(css|less)$': 'identity-obj-proxy',
}
Adding bellow line into jest.config.js file helped me to test pass,
"\\.(jpg|jpeg|png)$": "identity-obj-proxy",
Example:
moduleNameMapper: {
"\\.(css)$": "identity-obj-proxy",
"\\.(jpg|jpeg|png)$": "identity-obj-proxy",
},
If you want to use jest with webpack, you need to explicitly configure it as so. Take a look at this guide here: https://jestjs.io/docs/webpack
For those who use Vue test util in Nuxt 2 and are faced with question or this problem ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){ SyntaxError: Invalid or unexpected token
make a file with the name of fileTransformer.js in the test/unit directory, and then add these codes:
const path = require('path')
module.exports = {
process(src, filename, config, options) {
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'
},
}
and then add these codes to jest.config.js file:
transform: {
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/unit/fileTransformer.js',
// ... other configs
},
In case of IOS image names with #
moduleNameMapper: {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[#./a-zA-Z0-9$_-]+\\.(png|gif)$": "RelativeImageStub"
}
In React Native we use preset: 'react-native'
https://github.com/facebook/react-native/blob/main/jest-preset.js
Or add transform into jest.config.js
transform: {
'^.+\\.(js|ts|tsx)$': 'babel-jest',
'^.+\\.(bmp|gif|jpg|jpeg|mp4|png|psd|svg|webp)$': require.resolve(
'../node_modules/react-native/jest/assetFileTransformer.js',
),
},
If you do not use React Native, need to create a file https://github.com/facebook/react-native/blob/main/jest/assetFileTransformer.js into your project and changes path into require.resolve
Nothing has worked for me, so I replaced
the 'mount' with 'shallow' everywhere and it's working fine now.
npm install --save-dev identity-obj-proxy
and add the following inside your jest.config.js :
moduleNameMapper: {
"\\.(css)$": "identity-obj-proxy",
"\\.(jpg|jpeg|png)$": "identity-obj-proxy",
},
this worked for me .

SyntaxError with Jest and React and importing CSS files

I am trying to get my first Jest Test to pass with React and Babel.
I am getting the following error:
SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token
> 7 | #import '../variables.css';
| ^
My package.json config for jest look like this:
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"syntax-class-properties",
"transform-class-properties"
]
},
"jest": {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "RelativeImageStub"
},
"testPathIgnorePatterns": [
"/node_modules/"
],
"collectCoverage": true,
"verbose": true,
"modulePathIgnorePatterns": [
"rpmbuild"
],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react/",
"<rootDir>/node_modules/react-dom/",
"<rootDir>/node_modules/react-addons-test-utils/",
"<rootDir>/node_modules/fbjs",
"<rootDir>/node_modules/core-js"
]
},
So what am I missing?
moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.
Create a file like this in your project (you can use a different name or path if you’d like):
config/CSSStub.js
module.exports = {};
This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:
'^.+\\.(css|less)$': '<rootDir>/config/CSSStub.js'
Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.
Read more in this guide.
I solved this by using the moduleNameMapper key in the jest configurations in the package.json file
{
"jest":{
"moduleNameMapper":{
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
"\\.(gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
}
}
}
After this you will need to create the two files as described below
__mocks__/styleMock.js
module.exports = {};
__mocks__/fileMock.js
module.exports = 'test-file-stub';
If you are using CSS Modules then it's better to mock a proxy to enable className lookups.
hence your configurations will change to:
{
"jest":{
"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|scss|sass)$": "identity-obj-proxy"
},
}
}
But you will need to install identity-obj-proxy package as a dev dependancy i.e.
yarn add identity-obj-proxy -D
For more information. You can refer to the jest docs
UPDATE who use create-react-app from feb 2018.
You cannot override the moduleNameMapper in package.json but in jest.config.js it works, unfortunately i havent found any docs about this why it does.
So my jest.config.js look like this:
module.exports = {
...,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|sass|css)$": "identity-obj-proxy"
}
}
and it skips scss files and #import quite well.
Backing my answer i followed jest webpack
Similar situation, installing identity-object-proxy and adding it to my jest config for CSS is what worked for me.
//jest.config.js
module.exports = {
moduleNameMapper: {
"\\.(css|sass)$": "identity-obj-proxy",
},
};
The specific error I was seeing:
Jest encountered an unexpected token
/Users/foo/projects/crepl/components/atoms/button/styles.css:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button { }
^
SyntaxError: Unexpected token .
1 | import React from 'react';
> 2 | import styles from './styles.css';
If you're using ts-jest, none of the solutions above will work! You'll need to mock transform.
jest.config.js
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
roots: [
"<rootDir>/src"
],
transform: {
".(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest-config/file-mock.js",
'.(css|less)$': '<rootDir>/jest-config/style-mock.js'
},
};
file-mock.js
module.exports = {
process() {
return `module.exports = 'test-file-stub'`;
},
};
style-mock.js
module.exports = {
process() {
return 'module.exports = {};';
}
};
I found this working example if you want more details.
Solution of #import Unexpected token=:)
Install package:
npm i --save-dev identity-obj-proxy
Add in jest.config.js
module.exports = {
"moduleNameMapper": {
"\\.(css|less|scss)$": "identity-obj-proxy"
}
}
Update: Aug 2021
If you are using Next JS with TypeScript. Simply follow the examples repo.
Else you will be wasting days configuring the environment.
https://github.com/vercel/next.js/tree/canary/examples/with-jest
I added moduleNameMapper at the bottom of my package.json where I configured my jest just like this:
"jest": {
"verbose": true,
"moduleNameMapper": {
"\\.(scss|less)$": "<rootDir>/config/CSSStub.js"
}
}

Resources