How to configure Jest and babel-jest for specific folder - javascript

I'm getting the following error:
import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
The reason is that some module/s are not been compiled when published in npm.
I was wondering, how I can include them in the babel-jest compilation specific node_modules folder?
This is my current configuration in the package.json
"jest": {
"silent": false,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(scss|css|less)$": "<rootDir>/__mocks__/styleMock.js"
},
"setupFiles": [
"<rootDir>/__mocks__/localStorageMock.js"
],
"transform": {
"^.+\\.jsx$": "babel-jest",
"^.+\\.js$": "babel-jest"
}
I didn't find any solution in the documentation. It would be great if I can do something like this or something similar, adding which folder/s to transform:
"transformPaths": [ "path/to/file.js", "path/to/file.jsx"]

I got some help from the Jest guys,
Here is how to do it

Related

Jest import React from 'react': Syntax Error: Cannot use import statement outside a module

The error 'Support for the experimental syntax 'jsx' isn't currently enabled' is shown when I'm trying to run yarn test on my react file.
I have tried adding using this configuration:
package.json
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"transformIgnorePatterns": [
"node_modules/(?!axios)"
]
},
babel.config.js
module.exports = {
"presets": ["#babel/preset-react"]
};
After that I am still getting the error and it did not solve the problem.
Any suggestion? Thanks in advance!

SyntaxError: Unexpected token : when running jest test with Aurelia in TypeScript

Just created a new TypeScript Aurelia project using aurelia-cli .
Installed bootstrap and included bootstrap css in the app.ts using import.
import 'bootstrap/dist/css/bootstrap.min.css';
import '../../static/assets/css/app.scss';
import { routes } from './routes';
interface IApp {
message: string;
}
export class App implements IApp{
message = 'Hello World!';
}
Now when I run the test , I get error unexpected token as below
yarn test
# and the output contains
yarn run v1.12.3
$ nps test
nps is executing `test` : nps test.jest
nps is executing `test.jest` : node node_modules/rimraf/bin.js test/coverage-jest && jest
ts-jest[config] (WARN) TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.
FAIL test/unit/app.spec.ts
● 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 hav`enter code here`e 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.
SyntaxError: Unexpected token :
at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
at Object.<anonymous> (src/home/app.ts:163:1)
I commented the import bootstrap.css line in app.ts and everything runs fine.
Am I missing some configuration for jest to allow me to use css imports in .ts components?
Here is my jest portion from package.json
"jest": {
"verbose": true,
"roots": [
"<rootDir>/test"
],
"modulePaths": [
"<rootDir>/src",
"<rootDir>/node_modules"
],
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"transform": {
"^.+\\.ts$": "ts-jest"
},
"testRegex": "\\.spec\\.(ts|js)$",
"testPathIgnorePatterns": [
"build",
"dist",
"sample"
],
"setupFiles": [
"<rootDir>/test/jest-pretest.ts"
],
"testEnvironment": "node",
"collectCoverage": true,
"collectCoverageFrom": [
"src/**/*.{js,ts}",
"!**/*.spec.{js,ts}",
"!**/node_modules/**",
"!**/test/**"
],
"coverageDirectory": "<rootDir>/test/coverage-jest",
"coverageReporters": [
"json",
"lcov",
"text",
"html",
"clover"
]
},
I was getting the same error. I resolved my issue by changing the module compilerOption in tsconfig.json from "esnext" to "commonjs". Why am I getting “Unexpected token import” on one webpack project but not the other?

Why does Jest try to resolve every component in my index.ts?

So I'm using Jest (with Enzyme) to test a Typescript-React project, and am having an issue with an alias module.
I know the problem per se isn't finding the module, because it finds the module correctly. I think the problem may be the structure of one of my files.
jest.config.js
module.exports = {
"collectCoverage": false,
"collectCoverageFrom": [
"!**/*.d.ts",
"src/**/*.{js,jsx,ts,tsx}"
],
"coverageDirectory": "test",
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json",
"node"
],
"testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$",
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
"^.+\\.tsx?$": "ts-jest"
},
"transformIgnorePatterns": [
"[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$"
],
"resolver": "jest-webpack-resolver",
"moduleNameMapper": {
"^react-native$": "react-native-web",
"^components$": "<rootDir>/src/components",
"^reducers$": "<rootDir>/src/reducers",
"^actions$": "<rootDir>/src/actions",
"^selectors$": "<rootDir>/src/selectors",
"^services$": "<rootDir>/src/services",
"^views$": "<rootDir>/src/views",
"^domains$": "<rootDir>/src/domains"
},
};
Import used in my component being tested:
import { Label } from 'components';
My project structure leads the following way in components:
src
|_ components
|_ // ..various folders with React components
|_ index.ts
And my index.tsx basically looks like this:
export { default as Label } from './Label/Label'
// export other components
What's happening is the following:
When I run Jest, it resolves my 'components' module fine, it's the same in my webpack.alias, but what is breaking the test run is that it starts to 'build' (I'm not sure if it actually builds?) other components, and starts going up the dependency tree for some components I'm not even testing, and eventually breaks because it goes all the way up to my main index.tsx file that runs the entire app.
Is the problem the way I've structured my index.ts to export all my components?
I have the same problem. It seems to be related to jest having it's own module resolver. Maybe this helps: https://jestjs.io/docs/ecmascript-modules

CSS module #import fails the Jest test suit

I am using Jest and Enzyme to test my application. I am getting error:
FAIL app/containers/Navbar/NavbarContainer.test.js
● Test suite failed to run
app/components/Navbar/styles.css: Unexpected token (1:0)
> 1 | #import "../../styles/base/_variables";
| ^
2 |
3 | .navbar{
4 | width: $navbar-width;
This is my Jest configuration in package.json:
"jest": {
"verbose": true,
"globals": {
"env": {
"isProd": false,
"isDev": true,
"command": "start"
}
},
"moduleNameMapper": {
"\\.(css)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"js",
"jsx",
"json",
"css"
],
"modulePaths": [
"/app"
],
"moduleDirectories": [
"node_modules"
],
"verbose": true,
"setupFiles": [
"./setupJest.js"
],
"setupTestFrameworkScriptFile": "<rootDir>/setupTests.js"
}
I was following the guides while setting up the application, and I found that identity-obj-proxy will help to mock css-modules functionality, but that's not working in my case. Please let me know what am I missing here.
P.S. this is about not ES6 modules import. The suit failed because there is a #import in css.
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 why it does the trick.
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.
I added to devDependencies identity-obj-proxy
Backing my answer i followed jest webpack
So, I've found the solution to this problem. I was importing CSS without the extension in my components and Jest was confusing that import with JS file. Solution is instead of importing css like:
import * as styles from './styles'
you should import it like:
import * as styles from './styles.css'
One quick gotcha that I found with this. If you have a jest.config.js file, then you need to set your moduleNameWrapper inside of that config file.
I know this post is old but i solved this issue by adding jest-transform-css as a devDependency
npm i --save-dev jest-transform-css
and then adding the following inside jest.config.js
transform: {
'^.+\\.js$': 'babel-jest',
'.+\\.(css|styl|less|sass|scss)$': 'jest-transform-css'
}
you can refer to this github issue for more information

Jest configuration

I'm adding Jest Testing framework to my React Native project. I'm getting the following error:
Failed to get mock metadata: /Users/me/Documents/Development/project/node_modules/global/window.js
My test file looks like this:
import 'react-native'
import React from 'react'
import { MyComponent } from '../components/MyComponent'
import renderer from 'react-test-renderer'
it('renders correctly', () => {
const tree = renderer.create(<MyComponent />).toJSON()
expect(tree).toMatchSnapshot()
})
And also the Jest configuration in my package.json:
"jest": {
"preset": "jest-react-native",
"testPathIgnorePatterns": ["/node_modules/", "/example/", "/lib/"],
"testRegex": "(/tests/.*|\\.(test|spec))\\.(js|jsx)$",
"automock": "true",
"unmockedModulePathPatterns": [ "lodash" ],
"transformIgnorePatterns": [
"node_modules/(?!#exponent/ex-navigation",
")"
]
}
I had a look over http://facebook.github.io/jest/docs/manual-mocks.html#content as suggested on the error prompted.
I think something is wrong with your jest configuration in package.json.
Here is a sample jest config snippet:
"jest": {
"preset": "react-native",
"cacheDirectory": "./cache",
"coveragePathIgnorePatterns": [
"./app/utils/vendor"
],
"coverageThreshold": {
"global": {
"statements": 80
}
},
"transformIgnorePatterns": [
"/node_modules/(?!react-native|react-clone-referenced-element|react-navigation)"
]
}
preset: The preset is a node environment that mimics the environment of a React Native app. Because it doesn’t load any DOM or browser APIs, it greatly improves Jest’s startup time.
cacheDirectory: It helps you greatly improve the test speed. It does so by creating cache of compiled modules so that next time it doesn’t have to compile the node_modules while running tests.
coveragePathIgnorePatterns: Define the files which want to skip for coverage reports.
coverageThreshold: Defines the threshold limit for all the tests to pass. If the coverage is less than the defined limit, the tests would fail. This helped us to keep a good amount of coverage at all point of time.
transformIgnorePatterns: We pass all the NPM modules here which needs to be transpiled. These modules are basically ES6/7 modules.
PS: I have written a blog on how to setup jest for react-native project. Here is the URL : http://rahulgaba.com/react-native/2017/05/19/Jest-test-suite-with-superpowers.html
Set "automock": "false" in your package.json (automocking with the jest-react-native preset isn't supported)

Categories

Resources