【问题标题】:Setup Jest + React testing library using NextJS in TypeScript -- error setting upp jest.config.js在 TypeScript 中使用 NextJS 设置 Jest + React 测试库 -- 设置 upp jest.config.js 时出错
【发布时间】:2021-06-20 11:25:48
【问题描述】:

我正在尝试使用 NextJS 应用程序设置 Jest,目前在 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"
    }
  };

在我的setupTests.tsx 我有:

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

但是,当我运行 npm run test 时,我收到以下错误:

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

如果我删除 jest.config.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".

globals.css:2
    body {
         ^

    SyntaxError: Unexpected token '{'

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

cssscss 文件应该使用什么配置?

** 编辑 **

我确保 identity-obj-proxy 在我的 devDependencies 中,但是现在我收到一个错误:

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

【问题讨论】:

标签: javascript reactjs jestjs next.js


【解决方案1】:

试试这个:

  1. 使用此内容创建文件style-mock.js
module.exports = {};
  1. 在 jest config 的 moduleNameMapper 字段中指定它
moduleNameMapper: {
  '^.+\\.(css|less)$': '<rootDir>/jest-config/style-mock.js'
}

通过此设置,它将模拟所有 css 导入,希望对您有所帮助

【讨论】:

    【解决方案2】:

    您需要安装 identity-obj-proxy。运行 >>> yarn add -D identity-obj-proxy

    【讨论】:

    • 这让我更接近了。现在:错误类型错误:开玩笑:转换必须导出 processprocessAsync 函数。
    猜你喜欢
    • 2018-06-27
    • 2021-07-08
    • 2019-01-16
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多