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.
Related
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 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
The ES6 import works in this file, but generates an unexpected token import error when I'm importing relative files such as my Mongoose User model.
import mongoose from 'mongoose';
^^^^^^
SyntaxError: Unexpected token import
.babelrc
{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [
"transform-object-rest-spread",
"transform-async-to-generator",
"transform-export-extensions"
]
}
package.json
"ava": {
"require": [
"babel-register"
]
}
users.test.js
import test from 'ava'
import axios from 'axios'
import User from '../../models/user'
import { USER_REGISTRATION_ROUTES } from '../helpers/_test.properties.js'
test('user registration api works', async function (t) {
const email = `test${Date.now()}#example.com`
const userRegistrationData = {
email,
first_name: "john",
last_name: "doe",
password: "password"
}
await axios.post(USER_REGISTRATION_ROUTES, userRegistrationData)
.then(response => {
const data = response.data.data
const user = data.user
t.deepEqual(response.status, 200, 'Verify: response is successful')
t.deepEqual(data.registered, true, 'Verify: user is registered')
t.truthy(Object.keys(user).length > 0,
'Verify: if registered, user object is returned')
t.truthy(user.authentication_token,
'Verify: token is generated on successful registration')
})
.catch((err) => {
t.fail(`Cannot make requst to register user ${err}`)
})
User.remove({ email }, function (err) {
if (err) {
console.log('error')
} else {
console.log('success deleting test user')
}
})
})
Don't think import is supported in nodejs yet. You have to use require.
const mongoose = require('mongoose');
The answer that worked for me was the following suggested by Serge Seletskyy here. The es2017 preset is required for ES2017 features such as async await.
.babelrc
{
"presets": [
"es2017",
"#ava/stage-4",
"stage-3"
],
"plugins": [
"transform-runtime"
]
}
package.json
"ava": {
"require": [
"babel-register"
],
"babel": "inherit"
}
install modules
yarn add babel-register babel-preset-es2017 #ava/babel-preset-stage-4 babel-plugin-transform-runtime babel-preset-stage-3 --dev
Running ./node_modules/.bin/ava --verbose should now work
Non-test files are loaded through babel-register, which applies your .babelrc. However you've disabled module transpilation. I see in another comment that you're using Webpack. Try adding a environment config for Babel which restores module transpilation. From the top of my head:
{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [
"transform-object-rest-spread",
"transform-async-to-generator",
"transform-export-extensions"
],
"env": {
"test": {
"presets": [
["es2015", { "modules": true }]
]
}
}
}
This should work with the latest AVA version.
My version of Ava is 1.0.0-beta.4, and below is the solution that worked for me:
Add the following to your package.json
"ava": {
"require": [
"#babel/register"
]
}
Then npm install --save-dev #babel/register, and run test again.