How to setup jest with node_modules that use es6 - reactjs

I have a very simple test:
describe('sanity', () => {
it('sanity', () => {
expect(true).toBeTruthy()
})
})
And I'm receiving the following error:
FAIL spec/javascript/sanity_test.js
● 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 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:
/Users/piousbox/projects/ruby/<project>/node_modules/#atlaskit/tooltip/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { default } from './components/Tooltip';
^^^^^^
SyntaxError: Unexpected token export
3 | import update from "immutability-helper";
4 | import {components} from "react-select-2";
> 5 | import Tooltip from "#atlaskit/tooltip";
| ^
6 | const isEqual = require("react-fast-compare");
7 | import _, {replace} from "lodash";
8 | import { get } from "$shared/request";
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (app/javascript/customer2/components/fob/fob_utils.js:5:1)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 1.593s
I have this .babelrc:
{
"presets": ["#babel/react", "#babel/env"]
}
How do I make the trivial test pass?

Matt's answer is accepted b/c it is insightful. The change that did it for me was adding in package.json:
"jest": {
...
"transformIgnorePatterns": [
"node_modules/(?!#atlaskit)"
],
You can add support for multiple packages at once by separating them with a |
"jest": {
...
"transformIgnorePatterns": [
"node_modules/(?!module1|module2|etc)"
],

Two ways you can pass this test:
Option 1.) Setup your babel configuration to handle ES6 imports by add a testing env option (the testing environment flag will be defined in your package.json scripts, for example: "test": "NODE_ENV=testing jest" or "test": "BABEL_ENV=testing jest")...
babel.config.js
module.exports = api => {
api.cache(true);
return {
presets: ["#babel/preset-env", "#babel/preset-react"],
plugins: [
"#babel/plugin-transform-runtime",
["#babel/plugin-proposal-class-properties", { loose: true }],
],
env: {
testing: {
presets: [
[ "#babel/preset-env", { targets: { node: "current" }}],
],
},
},
};
};
Option 2.) Transpile the ES6 module into ES5 syntax in your webpack.config.js configuration:
webpack.config.js
const { NODE_ENV } = process.env
const inDevelopment = NODE_ENV === "development";
module.exports = {
...
module: {
rules: [
...
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
exclude: !inDevelopment ? /node_modules\/(?!(#atlaskit\/tooltip))/ : /(node_modules)/,
options: {
cacheDirectory: inDevelopment,
cacheCompression: false,
},
},
...
],
}
...
}
The major difference between the two options is that the first option will only work in a testing environment. If you try to use it in a development/production environment, it may impact other 3rd party packages and cause compilation errors. Therefore, if you plan on moving this into a production environment that supports IE11 and below, then the second option is recommended. HOWEVER, keep in mind that this will transpile the package every time a production build is created and/or a test suite is run. Therefore, if you're working on a very large project (or transpiling multiple ES6 packages), it can be quite resource heavy. Therefore, I'd recommend compiling the 3rd party package(s) from ES6 to ES5 and installing it/them locally or privately (via an NPM package).
Working example (this example includes the second option):
https://github.com/mattcarlotta/transpile-es6-module
To install:
cd ~/Desktop && git clone git#github.com:mattcarlotta/transpile-es6-module.git
cd transpile-es6-module
yarn install
yarn dev to run the demo
yarn test to run test suites

Related

Importing a react component into an existing react project from npm package

I have created an npm package with the scoped name '#bpmg/mycomponent' with a single react component. I have published this to a local npm registry (verdaccio).
I have created a new react project to test this package, using create-react-app.
I have installed my npm package successfully and can import the component into my project.
However, webpack (from create-react-app scripts) complains about my imported file.
support for the experimental syntax 'jsx' isn't currently enabled
So I install react-app-rewired and try to override the webpack config to "include" this one node_module in the webpack bundler.
Here is what I have
/* config-overrides.js */
const path = require('path');
module.exports = {
webpack: function (config, env) {
config.module.rules= [
{
test: /\.(js|jsx)$/,
exclude: /node_modules\/(?!(#bpmg)\/).*/,
include: [
path.join(__dirname, 'src')
],
loader: 'babel-loader',
options: { presets: ['#babel/env', '#babel/preset-react'] },
}
];
return config;
}
}
This fails to run
ERROR in ./node_modules/#bpmg/myComponent/src/myComponentMainFile.js
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
Where it chokes on the first bit of jsx syntax it encounters.
Where am I going wrong here?

Trying to test using jest but running into issues

Im trying to test a component using jest. The component imports spacetime npm module, which uses es-modules on main
https://www.npmjs.com/package/spacetime
I'm running into the following issues:
● Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• 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/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
/Users/wscott/dev/pm/client/node_modules/spacetime/src/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import Spacetime from './spacetime.js'
^^^^^^
SyntaxError: Cannot use import statement outside a module
6 | import search from '../../assets/images/search.svg';
7 | import Dropdown from 'react-bootstrap/Dropdown';
> 8 | import spacetime from "spacetime";
| ^
9 | import languages from "../../libraries/languages/language-list";
10 | import { Rating } from 'react-simple-star-rating';
11 |
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
at Object.<anonymous> (src/components/Mentor/MentorList.js:8:1)
Here's my jest.config.js file
module.exports = {
preset: 'ts-jest',
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
"^.+\\.(js|jsx)$": "babel-jest",
".+\\.(css|styl|less|sass|scss)$": "jest-transform-css"
},
"moduleNameMapper": {
"\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/src//__mocks__/fileMock.js"
},
"setupFiles":["./src/browserMocks.js"],
"globals": {
"window": {
location: {
href: ""
},
localStorage: {
getItem: () => {
}
}
},
"localStorage": {
getItem: () => {
}
}
}
};
Here's my babel.config.js file:
module.exports = {
presets:[
"#babel/preset-env",
"#babel/preset-react"
],
"env": {
"test": {
"plugins": ["#babel/plugin-transform-modules-commonjs"]
}
}
}
Can someone help?
Downgrading to 6.12.3 fixes the issue with jest. The issue is space time use es-module imports which jest doesn't support but downgrading should work
Try to set the transformIgnorePatterns property to let jest transform the file before tests:
transformIgnorePatterns: [
'node_modules/(?!(spacetime)/)',
],
This way you are telling to skip transformation for all your node_modules except spacetime, which will be transformed by babel-jest as is set in you configuration.

Hetting error in react build with webpack

I am using react.js & web pack. when run the NPM run build command get this error I am learning the how to make build with web pack so I try first time but getting this error. please help!
I write this code from some web pack tutorial website.
assets by status 1.05 KiB [cached] 2 assets
./src/index.js 796 bytes [built] [code generated] [1 error]
ERROR in ./src/index.js 13:2
Module parse failed: Unexpected token (13:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| const ProviderComponent = ()=>{
| return (
> <Provider store={store} >
| <App/>
| </Provider>
webpack 5.65.0 compiled with 1 error in 901 ms
npm ERR! code ELIFECYCLE
npm ERR! errno 1
Web pack file
const port = process.env.PORT || 8080;
const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');
module.exports = {
output :{
path:path.join(__dirname,'/dist'),
filename:'main.[fullhash].js'
},
module:{
rules:[{
test:/\.(js|jsx)$/,
exclude:/node_modules/,
},
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{ loader: 'less-loader' }
]
},
]
},
resolve:
{
mainFiles: ['index', 'Index'],
extensions: ['.js', '.jsx','.css'],
alias: {
'#': path.resolve(__dirname, 'src'),
}
},
plugins:[
new HtmlWebPackPlugin({
template:'./public/index.html'
})
],
devServer:{
host:'localhost',
port:port,
historyApiFallback:true,
open:true
}
}
You have JSX in your index.js which is not standard javascript. Webpack by default can only transpile standard javascript, for transpiling JSX which is a react feature, you need to use something that can help webpack recognize the syntax of JSX, webpack calls this things loaders.
There are different loaders which you can use, here for example you should use babel-loader to tell webpack how to understand JSX.
babel-loader internally uses Babel.js which is a library for transpiling non -standard javascript into standard javascript.
It's better to get familiar with Babel.js and then use it in webpack. But for now, what you need is this:
Install babel (with preset-react) and babel-loader
npm install -D babel-loader #babel/core #babel/preset-env #babel/preset-react
Add babel to your webpack js|jsx files rule
You can set babel options in the webpack config file like I'm doing here, or create a separate file for configuring babel itself. You can read more about it in Babel.js docs.
...
module:{
rules:[{
test:/\.(js|jsx)$/,
exclude:/node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', "#babel/preset-react"]
}
}
},
...

How to config webpack to transpile files from other lerna packages (ejected from create-react-app)

I'm trying to build a lerna package with a create-react-app package and a simple component library. My component is as follows:
import React, { Component } from "react";
import PropTypes from "prop-types";
class Layout extends Component {
render = () => {
let style = {
fontSize: 14,
fontFamily:
"-apple-system, system-ui, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, 'Helvetica Neue', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', sans-serif",
fontWeight: 400
};
return <div style={style}>{this.props.children}</div>;
};
}
export default Layout;
And my original create-react-app is as follows:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app/App/App';
ReactDOM.render(<App />, document.getElementById('root'));
App.js
import React, { Component } from "react";
import Layout from "#project/webux/lib/Layout";
class App extends Component {
render = () => {
return (
<Layout>
Hello!
</Layout>
);
};
}
export default App;
When running, I'm getting the following error:
../webux/lib/Layout/index.js
SyntaxError: /Volumes/workspace/dev/packages/webux/lib/Layout/index.js: Support for the experimental syntax 'classProperties' isn't currently enabled (5:12):
3 |
4 | class Layout extends Component {
> 5 | render = () => {
| ^
6 | let style = {
7 | fontSize: 14,
8 | fontFamily:
Add #babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.
This error happens because create-react-app does not transpile files outside its project. As my component Layout resides in another lerna package in another directory, it is not transpiled.
In order to solve it, I've ejected my create-react-app application and end up with the following webpack configuration file, where I've added the ====INCLUDED=== piece of code to set the input directories (I've added the directory immediately above the project, as this will point to my lerna \packages directory, so all packages files are processed:
...
resolve: {
// This allows you to set a fallback for where Webpack should look for modules.
// We placed these paths second because we want `node_modules` to "win"
// if there are any conflicts. This matches Node resolution mechanism.
// https://github.com/facebook/create-react-app/issues/253
modules: ['node_modules', paths.appNodeModules].concat(
modules.additionalModulePaths || []
),
// These are the reasonable defaults supported by the Node ecosystem.
// We also include JSX as a common component filename extension to support
// some tools, although we do not recommend using it, see:
// https://github.com/facebook/create-react-app/issues/290
// `web` extension prefixes have been added for better support
// for React Native Web.
extensions: paths.moduleFileExtensions
.map(ext => `.${ext}`)
.filter(ext => useTypeScript || !ext.includes('ts')),
alias: {
// Support React Native Web
// https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
'react-native': 'react-native-web',
// Allows for better profiling with ReactDevTools
...(isEnvProductionProfile && {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}),
...(modules.webpackAliases || {}),
},
plugins: [
// Adds support for installing with Plug'n'Play, leading to faster installs and adding
// guards against forgotten dependencies and such.
PnpWebpackPlugin,
// Prevents users from importing files from outside of src/ (or node_modules/).
// This often causes confusion because we only process files within src/ with babel.
// To fix this, we prevent you from importing files out of src/ -- if you'd like to,
// please link the files into your node_modules/ and let module-resolution kick in.
// Make sure your source files are compiled, as they will not be processed in any way.
new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
],
},
resolveLoader: {
plugins: [
// Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
// from the current package.
PnpWebpackPlugin.moduleLoader(module),
],
},
module: {
strictExportPresence: true,
rules: [
// Disable require.ensure as it's not a standard language feature.
{ parser: { requireEnsure: false } },
// First, run the linter.
// It's important to do this before Babel processes the JS.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
enforce: 'pre',
use: [
{
options: {
cache: true,
formatter: require.resolve('react-dev-utils/eslintFormatter'),
eslintPath: require.resolve('eslint'),
resolvePluginsRelativeTo: __dirname,
},
loader: require.resolve('eslint-loader'),
},
],
//=================== INCLUDED =====================/
//
// Included the lenrna packages directory (up directory)
// in order to transpile all files from other packages.
//
//===================================================
include: [path.resolve(__dirname, "../.."), paths.appSrc],
},
{
// "oneOf" will traverse all following loaders until one will
// match the requirements. When no loader matches it will fall
// back to the "file" loader at the end of the loader list.
oneOf: [
// "url" loader works like "file" loader except that it embeds assets
// smaller than specified limit in bytes as data URLs to avoid requests.
// A missing `test` is equivalent to a match.
{
test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
loader: require.resolve('url-loader'),
options: {
limit: imageInlineSizeLimit,
name: 'static/media/[name].[hash:8].[ext]',
},
},
// Process application JS with Babel.
// The preset includes JSX, Flow, TypeScript, and some ESnext features.
{
test: /\.(js|mjs|jsx|ts|tsx)$/,
/// Renato Mendes
/// This was added to support transpiling of monorepo modules.
/// See https://github.com/webpack/webpack/issues/6799
///
/// Original:
/// include: paths.appSrc
///
include: [path.resolve(__dirname, "../.."), path.resolve(paths.lernaRoot + "/packages"), paths.appSrc],
// include: paths.appSrc,
include: [paths.lernaRoot, paths.appSrc],
loader: require.resolve('babel-loader'),
options: {
customize: require.resolve(
'babel-preset-react-app/webpack-overrides'
),
plugins: [
[
require.resolve('babel-plugin-named-asset-import'),
{
loaderMap: {
svg: {
ReactComponent:
'#svgr/webpack?-svgo,+titleProp,+ref![path]',
},
},
},
],
],
// This is a feature of `babel-loader` for webpack (not Babel itself).
// It enables caching results in ./node_modules/.cache/babel-loader/
// directory for faster rebuilds.
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
compact: isEnvProduction,
},
},
// Process any JS outside of the app with Babel.
// Unlike the application JS, we only compile the standard ES features.
{
test: /\.(js|mjs)$/,
exclude: /#babel(?:\/|\\{1,2})runtime/,
loader: require.resolve('babel-loader'),
options: {
babelrc: false,
configFile: false,
compact: false,
presets: [
[
require.resolve('babel-preset-react-app/dependencies'),
{ helpers: true },
],
],
cacheDirectory: true,
// See #6846 for context on why cacheCompression is disabled
cacheCompression: false,
// If an error happens in a package, it's possible to be
// because it was compiled. Thus, we don't want the browser
// debugger to show the original code. Instead, the code
// being evaluated would be much more helpful.
sourceMaps: false,
},
},
// "postcss" loader applies autoprefixer to our CSS.
// "css" loader resolves paths in CSS and adds assets as dependencies.
// "style" loader turns CSS into JS modules that inject <style> tags.
// In production, we use MiniCSSExtractPlugin to extract that CSS
// to a file, but in development "style" loader enables hot editing
// of CSS.
// By default we support CSS Modules with the extension .module.css
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules (https://github.com/css-modules/css-modules)
// using the extension .module.css
{
test: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
}),
},
// Opt-in support for SASS (using .scss or .sass extensions).
// By default we support SASS Modules with the
// extensions .module.scss or .module.sass
{
test: sassRegex,
exclude: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
},
'sass-loader'
),
// Don't consider CSS imports dead code even if the
// containing package claims to have no side effects.
// Remove this when webpack adds a warning or an error for this.
// See https://github.com/webpack/webpack/issues/6571
sideEffects: true,
},
// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
test: sassModuleRegex,
use: getStyleLoaders(
{
importLoaders: 2,
sourceMap: isEnvProduction && shouldUseSourceMap,
modules: true,
getLocalIdent: getCSSModuleLocalIdent,
},
'sass-loader'
),
},
// "file" loader makes sure those assets get served by WebpackDevServer.
// When you `import` an asset, you get its (virtual) filename.
// In production, they would get copied to the `build` folder.
// This loader doesn't use a "test" so it will catch all modules
// that fall through the other loaders.
{
loader: require.resolve('file-loader'),
// Exclude `js` files to keep "css" loader working as it injects
// its runtime that would otherwise be processed through "file" loader.
// Also exclude `html` and `json` extensions so they get processed
// by webpacks internal loaders.
exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
},
// ** STOP ** Are you adding a new loader?
// Make sure to add the new loader(s) before the "file" loader.
],
},
],
}
...
I'm still getting the error, as my external component is not getting transpiled.
How to make the above webpack config transpile my code that resides in another package of my lerna project? Any other config missing? What am I doing wrong?
The bad news: This is a common problem. Create React App doesn't support monorepos, as of ~3.2.0 / late 2019. If you want to share components between lerna sibling packages, many people either avoid using "CRApp", or, include a build script in their component library packages and commit and export pre-transpiled ES5 files.
The good news: I found a fix that seems to work, and doesn't require ejecting CRA. Tested with both local build and test deploy to github pages.
It uses craco, which provides an API for editing CRA's webpack config without ejecting. Craco has plugins which add webpack loaders etc; we'll need craco-babel-loader:
npm i --save #craco/craco craco-babel-loader
...then there are some further CRACO setup steps, check https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation for the latest. At time of writing, you need to replace the following CRA scripts in package.json:
react-scripts start => craco start
react-scripts build => craco build
react-scripts test => craco test
Then we need to create a config file, craco.config.js, in the root of the CRA/craco package that receives ES6+ JSX components from sibling packages, and we need to list the package names to send to babel:
// crago.config.js
// see: https://github.com/sharegate/craco
const path = require('path')
const fs = require('fs')
const cracoBabelLoader = require('craco-babel-loader')
// Handle relative paths to sibling packages
const appDirectory = fs.realpathSync(process.cwd())
const resolvePackage = relativePath => path.resolve(appDirectory, relativePath)
module.exports = {
plugins: [
{
plugin: cracoBabelLoader,
options: {
includes: [
// No "unexpected token" error importing components from these lerna siblings:
resolvePackage('../some-component-library'),
resolvePackage('../more-components'),
resolvePackage('../another-components-package'),
],
},
},
],
}

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