簡體   English   中英

在 TypeScript 中使用 NextJS 設置 Jest + React 測試庫 — 設置 upp jest.config.js 時出錯

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

我正在嘗試使用 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";

您需要安裝 identity-obj-proxy。 運行 >>> yarn add -D identity-obj-proxy

嘗試這個:

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

通過此設置,它將模擬所有 css 導入,希望對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM