导入 css 时开玩笑的意外令牌 [英] jest unexpected token when importing css

查看:24
本文介绍了导入 css 时开玩笑的意外令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了 SyntaxError: Unexpected token 的错误.

在我的代码中

import 'react-dates/lib/css/_datepicker.css'

import 'semantic-ui-css/semantic.min.css'

那些不在我的 spec.js 中,而是在我的实现代码中,知道为什么吗?我运行我的应用程序没有问题,但是当我尝试运行测试时开玩笑抛出错误.

those isn't in my spec.js but my implementation code, any clue why? I have no problem running my app but jest throw error when I try to run test.

推荐答案

问题在于 Jest 正在访问这些 CSS 导入并试图将它们解析为 JavaScript.

The problem is that Jest is hitting these CSS imports and trying to parse them as if they were JavaScript.

意外令牌".消息可能是因为它阻塞的文件的第一行是 CSS 类声明,即 .datepicker: { ... }.

The "Unexpected token ." message probably comes because the first line of the file it is choking on is a CSS class declaration, i.e. .datepicker: { ... }.

无论如何,正如这个答案所指出的,解决这个问题的方法是创建一个包含模块的文件它导出一个空对象.我叫我的 styleMock.js.

Anyway, as pointed out in this answer, the way to get around this is to create a file containing a module which exports an empty object. I called mine styleMock.js.

module.exports = {};

然后,您需要在您的项目根目录中创建一个 jest.config.js 文件并添加:

Then, you need to create a jest.config.js file in your project root and add:

module.exports = {
  moduleNameMapper: {
    '\.(css|less)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
  }
};

moduleNameMapper 设置告诉 Jest 如何解释具有不同扩展名的文件.在这种情况下,我们只需要将它指向我们刚刚创建的空文件.显然,相应地调整文件的路径.

The moduleNameMapper setting tells Jest how to interpret files with different extensions. In this case we simply need to point it at the empty file we just created. Obviously adjust the path to your file accordingly.

请注意,您可以针对您需要的任何文件结尾扩展上面的正则表达式.我的看起来像:

And note that you can expand the regex above for whichever file endings you need. Mine looks like:

moduleNameMapper: {
  '\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
    '<rootDir>/test/jest/__mocks__/fileMock.js',
  '\.(css|less)$': '<rootDir>/test/jest/__mocks__/styleMock.js',
},

其中 fileMock.jsstyleMock.js

或者,您可以使用诸如 jest-transform-stub 之类的模块,它对你做同样的事情.

Alternatively, you could use a module such as jest-transform-stub, which does the same thing for you.

这篇关于导入 css 时开玩笑的意外令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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