简体   繁体   中英

Setup Jest + React testing library using NextJS in TypeScript — error setting upp jest.config.js

I am trying to set up Jest with a NextJS application, currently in jest.config.js :

module.exports = {
    testPathIgnorePatterns: ["<rootDir>/.next/", "node_modules/"],
    setupFilesAfterEnv: ["<rootDir>/__tests__/setupTests.tsx"],
    transform: {
      "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
      "\\.(css|less|scss|sass)$": "identity-obj-proxy"
    }
  };

In my setupTests.tsx I have:

import "@testing-library/jest-dom/extend-expect";

However when I run npm run test I get the following error:

  Module identity-obj-proxy in the transform option was not found.
         <rootDir> is: ....

If I remove the line in jest.config.js I get:

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".

globals.css:2
    body {
         ^

    SyntaxError: Unexpected token '{'

    > 5 | import "../styles/globals.css";

What configuration should I use for the css and scss files?

** EDIT **

I made sure that identity-obj-proxy is in my devDependencies however, now I get an error:

Test suite failed to run

   Test suite failed to run

    TypeError: Jest: a transform must export a `process` function.

    > 5 | import "../styles/globals.css";
        | ^
      6 | import React from "react";

You need to install identity-obj-proxy. Run >>> yarn add -D identity-obj-proxy

Try this:

  1. Create a file style-mock.js with this content
module.exports = {};
  1. Specify it inside the moduleNameMapper field of jest config
moduleNameMapper: {
  '^.+\\.(css|less)$': '<rootDir>/jest-config/style-mock.js'
}

With this setup, it will mock all css import, hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM