开玩笑试图解析 .css

jest trying to parse .css

我在开玩笑时遇到问题,无论我做什么,它都会一直尝试将 css 文件解析为 javascript。

使用 webpack 正确构建文件。

我有以下的玩笑配置

"jest": {
    "rootDir": "./src",
    "moduleNameMapper": {
      "^.*[.](css|CSS)$": "../jest/styleMock.js"
    }
  },

我还尝试了脚本预处理器从导入中删除 css:

 "jest": {
    "rootDir": "./src",
    "scriptPreprocessor": "../node_modules/jest-css-modules"
  },

一直报错。

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){.button {
                                                                                             ^
    SyntaxError: Unexpected token .

你试过了吗babel CLI

在我的预处理器中,我使用 babel-core->utils 中的 babel-corecanCompile 函数来转换我的代码,同时忽略除 .js、.es、.jsx 等之外的其他文件

var babel = require('babel-core');
var canCompile = babel.util.canCompile

module.exports = {
    process: function (src, filename) {
    if (!canCompile(filename)) {
        return ''; //ignore this file
    }

也许您的代码也没有转换,这就是为什么您有 SyntaxErrorbabel.transform)? Look also at custom preprocessor 开玩笑。

最好的解决方案是在 Jest 配置中使用 moduleNameMapper 行,如 described in the Jest docs.

package.json 中的最小 "ignore css" 玩笑配置可能会像这样

  "jest": {
    "moduleNameMapper": { "\.(css|less)$": "<rootDir>/assets/css/__mocks__/styleMock.js" }
  },

那么styleMock.js就是这个

module.exports = {};

我不知道这是不是最好的方法,但考虑到我已经在这里卡了一段时间,所以我发布了解决方案。

为了修复它,我必须执行两个步骤:

1) @Jonathan Stray 解决方案因此添加一个 moduleNameMapper 指向一个 js 模拟(有关详细信息,请参阅他的回复)

2) 然后我必须安装 jest-css-modules-transform 插件,并将其添加到 package.json 中的 jest 配置中,如下所示:

"jest": {
    //...
    "transform": {
        ".+\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform",
        //...
    },
    //...
}

我正在使用“jest-css-modules-transform”,它运行良好。

  1. 我必须安装 jest-css-modules-transform 插件 :
npm i --save-dev jest-css-modules-transform

或用纱线

yarn add -D jest-css-modules-transform
  1. 然后在jest.config.s里面的jest配置中添加如下:
module.exports = {
    testPathIgnorePatterns: ["<rootDir>/.next/", "<rootDir>/node_modules/"],
    setupFilesAfterEnv: ["<rootDir>/setupTests.tsx"],
    transform: {
        "^.+\.(js|jsx|ts|tsx)$": "<rootDir>/node_modules/babel-jest",
        '.+\.(css|styl|less|sass|scss)$': 'jest-css-modules-transform'
    }
};