I am having issues in running jest tests in my project with Babel7. Tests used to transpile perfectly with babel6. It also compiles perfectly with webpack with Babel7 but fails to run tests with jest due to a transpilation error. What am I doing wrong?
react/node_modules/generic-redux-root/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './source/CreateReduxRoot';
^^^^^^
SyntaxError: Unexpected token export
my jest config
{
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
"<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/fbjs",
"enzyme"
],
"roots": [
"<rootDir>/__tests__"
],
"transformIgnorePatterns": [
"node_modules/(^generic-)/i", //a module matching this is throwing an error
"node_modules/react-infinite-scroller"
],
"setupFiles": [
"./jestsetup.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"testResultsProcessor": "./jestTrxProcessor",
"verbose": true
}
My .babelrc
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"ie": 11
},
"useBuiltIns": "usage"
}
],
"#babel/preset-react"
],
"plugins": [
"#babel/plugin-transform-runtime",
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-syntax-import-meta",
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-json-strings",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
"#babel/plugin-proposal-function-sent",
"#babel/plugin-proposal-export-namespace-from",
"#babel/plugin-proposal-numeric-separator",
"#babel/plugin-proposal-throw-expressions",
"#babel/plugin-proposal-object-rest-spread",
"#babel/plugin-transform-object-assign"
]
}
What am I doing wrong?
This is happening because Babel 7 no longer loads your .babelrc automatically.
There is a new concept of root config which should be located in the root of your project and the file must be named babel.config.js and export an object.
So to give you some steps to follow:
rename your .babelrc to babel.config.js and make sure you use module.exports = {...}
run jest --clearCache to clear Jest internal cache (which costed me a few hours of banging my head against the wall)
At this point your babel config should be loaded correctly by Jest
Related
Hi i am using angular 11 and ionic 5 ;
for ionic storage i am using #ionic/storage-angular:^3.0.6 module.
during jest unit tests i am getting
Cannot find module '#ionic/storage' from
'node_modules/#ionic/storage-angular/bundles/ionic-storage-angular.umd.js'
#ionic/storage-angular is a dependency in one of the service which i mocked
jest.confi.js has
transformIgnorePatterns: [
'./node_modules/(?!#ionic|ngx-socket-io/|!#ionic/storage-angular)'
]
spec file mocking the service
let storeServiceStub={
get:jest.fn().mockResolvedValue({})
};
await TestBed.configureTestingModule({
declarations: [ DataSyncComponent ],
providers:[
{ provide: StoreService, useValue: storeServiceStub },
]
})
.compileComponents();
#ionic/storage-angular is a of store service which i m replacing with stub;
testing env to repo bug
package.json
dependencies:{
...
"#ionic/storage-angular": "^3.0.6",
...
}
devDependencies:{
...
"jest": "^27.0.3",
"jest-preset-angular": "^9.0.1",
"#types/jest": "^26.0.23",
...
}
node v 14
os osx 11.2.2
I can fix it by adding the following configuration in my jest.config.js
moduleNameMapper: {
'^#ionic/storage': '<rootDir>/node_modules/#ionic/storage/dist/esm/index.d.ts',
},
Quite similar to the answer from #Ferraria. But the module name starts with the character ^ and the path ends in index.d.ts.
My complete configuration is
module.exports = {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": ["<rootDir>/setup-jest.ts"],
"transformIgnorePatterns": [
"node_modules/(?!#ngrx|#ionic-native|#ionic)"
],
moduleNameMapper: {
'^#ionic/storage': '<rootDir>/node_modules/#ionic/storage/dist/esm/index.d.ts',
},
setupFiles: ["jest-canvas-mock"]
};
Provide the jest moduleNameMapper for #ionic/storage in your jest.config.js like this:
...,
transformIgnorePatterns: [
'./node_modules/(?!#ionic|ngx-socket-io/|!#ionic/storage-angular)'
],
"moduleNameMapper": {
"#ionic/storage": "<rootDir>/node_modules/#ionic/storage/dist/esm"
}
You can find more information for moduleNameMapper here.
I am trying to test my Next.js project with Jest and Enzyme. When I try to import a file from my components to test it, throws error though. Here's my files...
In the package.json my jest configuration are:
"jest": {
"setupFilesAfterEnv": "<rootDir>/jest.setup.js",
"testPathIgnorePatterns": [
"<rootDir>/.next/",
"<rootDir>/node_modules/"
],
"transform": {
"\\.(gql|graphql)$": "jest-transform-graphql",
".*": "babel-jest",
"^.+\\.js?$": "babel-jest"
}
},
"//": "I prefer this over a .babelrc file",
"babel": {
"env": {
"development": {
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true
}
]
]
},
"production": {
"presets": [
"next/babel"
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true
}
]
]
},
"test": {
"presets": [
[
"next/babel",
{
"preset-env": {
"modules": "commonjs"
}
}
]
],
"plugins": [
[
"styled-components",
{
"ssr": true,
"displayName": true
}
]
]
}
}
}
And subsequently in jest.setup.js :
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
However I always encounter this error anytime I want to **import a file **(In here for example I try to import a file namely "import ItemComponent from '../components/Item';"):
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". SyntaxError: Unexpected
identifier
Details:
SyntaxError: C:\Users\Welcome\Desktop\Advanced-React-master\sick-fits\frontend\__tests__\Item.test.js: Unexpected token (20:28)
18 | describe('<Item/>', () => {
19 | it('renders and matches the snapshot', () => {
> 20 | const wrapper = shallow(<ItemComponent item={fakeItem} />);
| ^
21 | expect(wrapper).toMatchSnapshot();
22 | });
23 | // it('renders and displays properly', () => {
at Parser.raise (node_modules/#babel/parser/lib/index.js:3939:15)
at Parser.unexpected (node_modules/#babel/parser/lib/index.js:5248:16)
at Parser.parseExprAtom (node_modules/#babel/parser/lib/index.js:6328:20)
at Parser.parseExprSubscripts (node_modules/#babel/parser/lib/index.js:5924:21)
at Parser.parseMaybeUnary (node_modules/#babel/parser/lib/index.js:5903:21)
at Parser.parseExprOps (node_modules/#babel/parser/lib/index.js:5812:21)
at Parser.parseMaybeConditional (node_modules/#babel/parser/lib/index.js:5784:21)
at Parser.parseMaybeAssign (node_modules/#babel/parser/lib/index.js:5731:21)
at Parser.parseExprListItem (node_modules/#babel/parser/lib/index.js:6995:18)
at Parser.parseCallExpressionArguments (node_modules/#babel/parser/lib/index.js:6124:22)
Any help would be appreciated
Try removing these two lines from your package.json:
".*": "babel-jest",
"^.+\\.js?$": "babel-jest"
In theory, these shouldn't be needed: https://jestjs.io/docs/en/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
The custom configuration you have added might be causing issues. In theory, jest should transform your js files by default using babel-jest. I've certainly had a recent NextJS project work with jest with no babel-jest config declared in my package.json.
I have been researching and testing for months and I cannot set up my can js v2.3 app to run test with jest, and I couldn't find any clue into what is my problem.
every time I perform test with a module importing can, jest returns a failed error with this message:
Also checked in npm can/map/ I don't see index.js file or an export and I was thinking that this might've caused the issue:
My .babelrc file contains:
{
"presets": [
"#babel/preset-env",
]
}
and my babel.config.js :
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
Any help is appreciated, thanks.
After upgrading from Jest 23.6.0 to 24.0.0 I'm getting this error: Plugin/Preset files are not allowed to export objects, only functions.
This is caused by this commit: https://github.com/facebook/jest/pull/7203/files
which documents the breaking change.
For those of us using require, it's not clear on what change we need to make in our repos to fix this.
There are a number of similar questions here on Stack Overflow but none of them have lead me to the solution yet...
Recently I had the same issue working with Jest 24.0.0. This is what I did to have it running.
First I installed the dependencies as they explain in the docs, but I used npm insted of yarn.
npm install --save-dev babel-jest #babel/core #babel/preset-env
Then I had to add a file called babel.config.js with this content:
// babel.config.js
module.exports = {
presets: [
[
'#babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
};
And then it started to work correclty. I hope this can help.
presets[0][1] must be an object. ================ important
{
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
},
"react"
]
],
"plugins": [
"transform-object-rest-spread",
"transform-class-properties"
]
}
<!-- end snippet -->
Try adding/updating .babelrc
with
{
"presets": [
[
"#babel/preset-env",
{
"targets": {
"node": "current"
}
}
]
]
}
I'm using WebPack, Babel and React. I have a folder structure like the below
node_modules/
.babelrc
package.json
SomeThirdPartyFolder/
node_modules/
package.json
src/
FileA.js
I wanted to use FileA which has jsx content, however it acted as though Babel wasn't there, i.e. it produced a compile error on the below
return (
<div className etc
If I remove the package.json in SomeThirdPartyFolder then it does compile
Clearly this isn't a real situation but I'd like to understand what's happening here
(Based off loganfsmyth's comments)
I've converted the .babelrc file into a babel.config.js file and it now seems to work. The .babelrc file was
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
And the replacement file is
module.exports = function (api)
{
api.cache(true);
const presets = [
"#babel/preset-env",
"#babel/preset-react"
];
const plugins = [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
];
return {
presets,
plugins
};
}