带有 Jest 和 React 的 SyntaxError 并导入 CSS 文件 [英] SyntaxError with Jest and React and importing CSS files

查看:29
本文介绍了带有 Jest 和 React 的 SyntaxError 并导入 CSS 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 React 和 Babel 通过我的第一个 Jest 测试.

I am trying to get my first Jest Test to pass with React and Babel.

我收到以下错误:

语法错误:/Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less:意外令牌

SyntaxError: /Users/manueldupont/test/avid-sibelius-publishing-viewer/src/components/TransportButton/TransportButton.less: Unexpected token

    >  7 | @import '../variables.css';
          | ^

我的 package.json 配置 jest 如下所示:

My package.json config for jest look like this:

"babel": {
    "presets": [
      "es2015",
      "react"
    ],
    "plugins": [
      "syntax-class-properties",
      "transform-class-properties"
    ]
  },
  "jest": {
    "moduleNameMapper": {
      "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
      "^[./a-zA-Z0-9$_-]+\.png$": "RelativeImageStub"
    },
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "collectCoverage": true,
    "verbose": true,
    "modulePathIgnorePatterns": [
      "rpmbuild"
    ],
    "unmockedModulePathPatterns": [
      "<rootDir>/node_modules/react/",
      "<rootDir>/node_modules/react-dom/",
      "<rootDir>/node_modules/react-addons-test-utils/",
      "<rootDir>/node_modules/fbjs",
      "<rootDir>/node_modules/core-js"
    ]
  },

那我错过了什么?

推荐答案

moduleNameMapper 是告诉 Jest 如何解释具有不同扩展名的文件的设置.你需要告诉它如何处理Less文件.

moduleNameMapper is the setting that tells Jest how to interpret files with different extension. You need to tell it how to handle Less files.

在您的项目中创建一个这样的文件(如果您愿意,可以使用不同的名称或路径):

Create a file like this in your project (you can use a different name or path if you’d like):

module.exports = {};

这个存根是我们将告诉 Jest 使用的模块,而不是 CSS 或 Less 文件.然后更改 moduleNameMapper 设置并将此行添加到其对象中以使用它:

This stub is the module we will tell Jest to use instead of CSS or Less files. Then change moduleNameMapper setting and add this line to its object to use it:

'^.+\.(css|less)$': '<rootDir>/config/CSSStub.js'

现在 Jest 会将任何 CSS 或 Less 文件视为导出空对象的模块.您也可以做其他事情——例如,如果您使用 CSS 模块,您可以使用代理,以便每次导入都返回导入的属性名称.

Now Jest will treat any CSS or Less file as a module exporting an empty object. You can do something else too—for example, if you use CSS Modules, you can use a Proxy so every import returns the imported property name.

在此指南中阅读更多内容.

这篇关于带有 Jest 和 React 的 SyntaxError 并导入 CSS 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆