Jest didn't parse to import a file - jestjs

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.

Related

How to fix that eslint complain about typescript's path aliasing

I try to import interfaces like this
import placeholder from '#/assets/images/placeholder-image.svg'
import { Button } from '#/components/atoms/buttons/Button'
but they get es-lint complain Like this.
and
Missing file extension for "#/components/atoms/buttons/Button"eslintimport/extensions
Unable to resolve path to module '#/components/atoms/buttons/Button'.eslintimport/no-unresolved
My .babelrc file is
"presets": ["#babel/react", "#babel/preset-typescript"],
"plugins": [
"#babel/plugin-transform-typescript",
"babel-plugin-typescript-to-proptypes",
"#babel/plugin-proposal-export-default-from",
["#babel/plugin-proposal-class-properties", { "loose": true }],
"#babel/plugin-proposal-object-rest-spread",
["#babel/plugin-proposal-private-methods", { "loose": true }],
["#babel/plugin-proposal-private-property-in-object", { "loose": true }],
[
"module-resolver",
{
// https://stackoverflow.com/a/57288642/2298548
"root": ["."],
"alias": {
"#/svg": "./src/svg",
"#/utils": "./src/utils",
"#/hooks": "./src/hooks",
"#/doc": "./src/doc",
"#/config": "./config",
"#/styles": "./src/styles",
"#/fonts": "./src/assets/fonts",
"#/components": "./src/components",
"#/SVGIcons": "./src/SVGIcons",
"#/base": "./src",
"#/assets": "./src/assets"
}
}
]
]
}
and my .eslintrc.js is
settings: {
'import/resolver': {
node: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],
},
},
},
Does anyone have an idea for this why happen?
In path alias how we have to find a solution for linter error without disable es-lint.
Try declaring a type and then import it, check this link.
declare module '*.svg' {
import * as React from 'react';
export const ReactComponent: React.FunctionComponent<React.SVGProps<SVGSVGElement>>;
const src: string;
export default src;
}
If the above commented solution doesn't work you might need to disable it temporary:
rules: {
'import/no-unresolved': [
'error',
{
'ignore': [ '\.svg' ]
}
]
}

Jest testing with angular ionic storage is failing

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.

Jest tests crash when due to #babylon/core es6 syntax

I'm trying to load a 3d scene in react with babylonjs. And this works excellently in my React app but I am getting failed tests from tests that have previously been passing with the following errors. I have tried exempting babylon from transformations but I am still failing.
● Test suite failed to run
Jest encountered an unexpected token
SyntaxError: Unexpected token export
at compileFunction (<anonymous>)
4 | import styled, { withTheme } from 'styled-components'
5 | import { observer, inject } from 'mobx-react'
> 6 | import * as BABYLON from '#babylonjs/core'
| ^
7 | import { GLTFFileLoader } from '#babylonjs/loaders/glTF/glTFFileLoader'
8 | import '#babylonjs/loaders/glTF'
9 | import '#babylonjs/materials/custom'
Here is my webpack configuration file
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
},
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
rootMode: 'upward',
presets: [
'#babel/preset-env',
'#babel/react',
{
plugins: [
'#babel/plugin-proposal-class-properties',
],
},
],
},
},
],
},
{
test: /\.css$/,
exclude: /node_modules/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
},
],
},
],
},
mode: 'development',
devtool: 'inline-source-map',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
devServer: {
contentBase: path.join(__dirname, 'public'),
hot: true,
port: 3000,
open: true,
historyApiFallback: true,
},
}
Here is my babel configuration.
{
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true }],
"#babel/plugin-proposal-optional-chaining",
"#babel/plugin-transform-runtime",
[
"styled-components",
{ "ssr": false, "displayName": true, "preprocess": false }
]
],
"env": {
"production": {
"plugins": [
["react-remove-properties", { "properties": ["data-testid"] }]
]
},
"test": {
"presets": ["#babel/preset-env", "#babel/preset-react"],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-transform-modules-commonjs"
]
}
}
}
Here is my jest configuration
{
"setupFilesAfterEnv": ["jest-expect-message"],
"transformIgnorePatterns": ["/node_modules/(?!#babylonjs)"],
"transform": {
"^.+\\.js$": "babel-jest",
"^.+\\.ts$": "ts-jest"
},
"globals": {
"NODE_ENV": "test"
}
}
I found since I was in a mono-repo structure, I had to change from .babelrc to babel.config.js as recommended in jest docs. This solved the issue of transforming the esNext syntax in the #babylonjs modules
For those who aren't using babel this can be achieved with vanilla ts-jest. Be warned, this can add up to a minute to the initial load time for your tests because jest has to transform the babylonjs library.
const config = {
...
//SLOW - transform javascript
preset: 'ts-jest/presets/js-with-ts-esm',
//SLOW - transform node modules
transformIgnorePatterns: []
}
``

Babel7 Jest unexpected token export

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

Cannot get ava transpile to work with relatively-imported files

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.

Resources