Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How configure Jest when using react-app-rewired and customize-cra?

I am trying set up tests with Jest in a create-react-app that is using the override function from customize-cra and react-app-rewired. I have set up a relative path alias and when I run tests it throwing the error cannot find module

here is the code...

// LoginForm.test.js

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import LoginForm from './LoginForm';


it('submits', () => {
  const onSubmit = jest.fn();
  const { getByText } = render(<LoginForm onSubmit={onSubmit} />);
  fireEvent.click(getByText('Log in'));
  expect(onSubmit).toHaveBeenCalled();
});

// config-overrides.js

const {
  override,
  fixBabelImports,
  addLessLoader,
  addBabelPlugin
} = require("customize-cra");

module.exports = override(
  fixBabelImports("import", [
    {
      libraryName: "antd",
      libraryDirectory: "es"
      // style: true,
    },
    {
      libraryName: "ant-design-pro",
      libraryDirectory: "lib"
      // style: true,
    }
  ]),

  addBabelPlugin([
    "babel-plugin-root-import",
    {
      rootPathSuffix: "./src"
    }
  ]),

  addLessLoader({
    javascriptEnabled: true,
    modifyVars: {
      "@select-item-selected-font-weight": "500",
      "@font-family":
        '"Futura W01", "Futura", -apple -system, BlinkMacSystemFont, "Segoe UI", sans-serif',
      "@pagination-font-family":
        '"Futura W01", "Futura", -apple -system, BlinkMacSystemFont, "Segoe UI", sans-serif',
      "@statistic-font-family":
        '"Futura W01", "Futura", -apple -system, BlinkMacSystemFont, "Segoe UI", sans-serif'
    }
  })
);

Any pointers much appreciated, thank you.

like image 436
Frederick Duffield Avatar asked Jun 12 '19 11:06

Frederick Duffield


1 Answers

This is maybe a bit old but I just came across it and solved it so maybe it can help other people.

React app rewired uses react-scripts under the hood so it will not pick up your webpack configuration files. However there is a way to customize it, you can put your jest configuration in the root of your package.json:

"jest": {
    "moduleNameMapper": {
        "^@app(.*)$": "<rootDir>/src/ui/app$1"
    },
    "setupFiles": [
       "<rootDir>/config/jest/setupTests.js"
    ]
}

You can see that react-script is picking up this config if you go to the source code of react-scripts/scripts/test and see that it is creating the jest config:

const createJestConfig = require('./utils/createJestConfig');

And that file overrides the default configuration with the jest config in your package.json:

const overrides = Object.assign({}, require(paths.appPackageJson).jest);

Where paths.appPackageJson is your package.json

like image 90
A. Llorente Avatar answered Nov 15 '22 12:11

A. Llorente