使用TypeScript在NextJS中设置Jest + React测试库 - 设置jest.config.js时出错。

3

我正在尝试在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 文件?

** 编辑 **

我确保在我的 devDependencies 中有 identity-obj-proxy,但现在出现错误:

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

这个帮助回答了你的问题吗:Jest无法找到模块FileName.css(映射为identity-obj-proxy) - juliomalves
@juliomalves 我确保将其添加到我的 devDependencies 中,但仍然出现关于 CSS 的错误。 - ashes999
@ashes999 你找到这个错误的解决方案了吗? - EternalObserver
2个回答

2

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


这让我更接近了。现在出错了:错误类型错误:Jest:转换必须导出一个processprocessAsync函数。 - Urasquirrel

0

试试这个:

  1. 创建一个名为 style-mock.js 的文件,并将以下内容复制进去
module.exports = {};
  1. 在 Jest 配置文件的 moduleNameMapper 字段中指定它
moduleNameMapper: {
  '^.+\\.(css|less)$': '<rootDir>/jest-config/style-mock.js'
}

通过这个设置,它将模拟所有的 CSS 导入,希望能够帮到您


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接