Jest和React并导入CSS文件时出现SyntaxError [英] SyntaxError with Jest and React and importing CSS files

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

问题描述

我正在尝试让我的第一个玩笑测试与React和Babel一起通过.

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

我遇到以下错误:

SyntaxError:/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配置看起来像这样:

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如何解释具有不同扩展名的文件的设置.您需要告诉它如何处理更少的文件.

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模块,则可以使用Proxy,这样每次导入都会返回导入的属性名称.

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.

请参阅此指南中的更多内容.

Read more in this guide.

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

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