Jest to vitest migration error; equivalent of moduleNameMapper - reactjs

I am trying to migrate from jest to vitest.
at some point I get this error :
Syntax Error: Invalid or unexpected token
It seems one of the packages we have in project has this line that causes the issue:
require("./lib/somefont.woff")
I checked jest and jest has this line which resolved the issue:
"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"
},
I was wondering how I can resolve the issue in vitest?
is there an equivalent of moduleNameMapper in vitest?

Use import to import the font
import "./lib/somefont.woff"
Try setting alias config in vitest.config.js
import { defineConfig } from 'vite'
export default defineConfig({
test: {
globals: true,
environment: "jsdom",
alias: {
".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
},
},
});

Related

Jest failed to parse file. Get data from subfolder in a package

I want to get access to data from subfolder in the package and the application works fine, but I got errors for npm run tests
I want to import like this:
import MyContext from "somePackageName/dist/es/context/MyContext";
But Jest allows me to use it in this way only:
import somePackageName from "somePackageName";
What should I add\change in jest config file to run tests without errors?
current jest.config.js:
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",
"\\.(css|less|sass|scss)$": "<rootDir>/__mocks__/styleMock.js",
},
transform: {
"^.+\\.(js|jsx)?$": "babel-jest",
},
transformIgnorePatterns: ["<rootDir>/node_modules/"],
testEnvironment: "jsdom",
setupFiles: ["<rootDir>/.jest/setEnvVars.js"],
};

JEST Cannot find module 'typescript-cookie'

I'm trying to run some tests in a project that was created using VITE + TS, and I'm getting the following error:
The module typescript-cookie is the only one it's not being found. If remove this module all tests work fine!
My jest.config.ts
module.exports = {
testEnvironment: 'jest-environment-jsdom',
collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx}'],
coverageDirectory: 'coverage',
setupFilesAfterEnv: ['<rootDir>/src/config/jest-setup.ts'],
transformIgnorePatterns: ['/node_modules/(?!#element)/'],
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
},
moduleNameMapper: {
'#hooks': ['<rootDir>/src/commons/hooks'],
'#contexts': ['<rootDir>/src/commons/contexts'],
'#commons': ['<rootDir>/src/commons'],
'#mock': ['<rootDir>/src/commons/mock'],
'#common/components': ['<rootDir>/src/commons/components'],
'#enum': ['<rootDir>/src/commons/enum/'],
'#interfaces': ['<rootDir>/src/commons/interfaces/'],
'#utils': ['<rootDir>/src/commons/utils/'],
'#mainRoutes': ['<rootDir>/src/router'],
'#services': ['<rootDir>/src/commons/services'],
},
};
vite.config.ts
import react from '#vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'#hooks': '/src/commons/hooks',
'#enum': '/src/commons/enum',
'#mock': '/src/commons/mock',
'#common/components': '/src/commons/components',
'#services': '/src/commons/services',
'#common': '/src/commons',
'#contexts': '/src/commons/contexts',
'#interfaces': '/src/commons/interfaces',
'#utils': '/src/commons/utils',
'#mainRoutes': '/src/router',
},
},
});
```
I've been experiencing the same error in a project that was created with Create React App. Assuming it's an issue with the library, I filed a bug report.
https://github.com/carhartl/typescript-cookie/issues/110

React Testing library custom setup import test-utils: module not installed. Unable to resolve path

I'm trying to configure jest absolute path for my custom test-utils directory (https://testing-library.com/docs/react-testing-library/setup#configuring-jest-with-test-utils), but I get the error Cannot find module 'test-utils' / unable to resolve path
My folder tree
-src/
--utils/
---test-utils/
----test-utils.js
----custom-queries.js
-jest.config.js
-jsconfig.json
My jest.config.js
module.exports = {
transform: {
'^.+\\.jsx?$': 'babel-jest',
},
testEnvironment: 'jsdom',
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
},
moduleDirectories: [
'node_modules',
'src',
'utils',
'test-utils',
],
};
My jsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"test-utils": ["./utils/test-utils"]
}
},
"include": ["src"],
"exclude": ["node_modules"]
}
My component test
import { render } from 'test-utils';
import React from 'react';
import '#testing-library/jest-dom/extend-expect';
import Alert from './alert';
describe('Alert', () => {
test('Renders Alert component', () => {
const { getByRole } = render(<Alert message="Success!" />);
const alert = getByRole(/alert/);
expect(alert).toHaveTextContent('Success!');
});
});
The test-utils is your custom module for which you specify path alias and how to resolve it in jsconfig.json as follows:
"compilerOptions":{
"baseUrl":"src",
"paths":{
"test-utils": ["./utils/test-utils"]
}
}
The same way you need to tell to Jest how to resolve it with moduleNameMapper option in your jest.config.js as follows:
moduleNameMapper: {
'test-utils/(.*)": "<rootDir>/src/utils/test-utils/$1',
},
For official documentation see: https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring
For similar issues see: Jest not finding alias path, React: Jest configuration Issue with Path Aliases and How to use path alias in a react project with Typescript + Jest

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.

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