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

Posted

技术标签:

【中文标题】在 TypeScript 中使用 NextJS 设置 Jest + React 测试库 -- 设置 upp jest.config.js 时出错【英文标题】:Setup Jest + React testing library using NextJS in TypeScript -- error setting 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";

【问题讨论】:

这是否有助于回答您的问题:Jest Could not locate module FileName.css (mapped as identity-obj-proxy)? @juliomalves 我确保我的 devDependencies 中有它,但我仍然收到有关 css 的错误 【参考方案1】:

试试这个:

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

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

【讨论】:

【参考方案2】:

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

【讨论】:

这让我更接近了。现在:错误类型错误:开玩笑:转换必须导出 processprocessAsync 函数。

以上是关于在 TypeScript 中使用 NextJS 设置 Jest + React 测试库 -- 设置 upp jest.config.js 时出错的主要内容,如果未能解决你的问题,请参考以下文章

暗模式在带有 Nextjs 和 Typescript 的 Tailwind CSS V3 中不起作用

如何使用tailwindcss将样式文件夹移动到nextjs typescript中的src文件夹?

TypeScript+NextJS 解构

NextJS Typescript - 设置 tslint 配置以在有未使用的导入/声明时强制出错

NextJS _app.tsx Component 和 pageProps 应该是啥 TypeScript 类型?

Nextjs 和 TypeScript 中的条件渲染不起作用