测试时让 Jest 忽略 .less 导入 [英] Make Jest ignore the .less import when testing

查看:28
本文介绍了测试时让 Jest 忽略 .less 导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Jest 对 React 组件运行一些非常简单的测试.由于组件文件顶部的这一行,我遇到了问题

I am trying to run some very simple tests on react components with Jest. I am running into problems because of this line at the top of my component file

import {} from './style.less';

此处的导入不需要测试,理想情况下会从测试中忽略.

The import here doesn't need to be tested and would ideally be ignored from the test.

当测试通过 npm test 运行时,我得到响应

When the test is run via npm test I get the response

FAIL tests/app_test.js ● 运行时错误 SyntaxError: Unexpected令牌 { 在文件 'client/components/app/style.less' 中.

FAIL tests/app_test.js ● Runtime Error SyntaxError: Unexpected token { in file 'client/components/app/style.less'.

确保您的预处理器设置正确,并确保您的'preprocessorIgnorePatterns' 配置正确:http://facebook.github.io/jest/docs/api.html#preprocessorignorepatterns-array-string如果您当前正在设置 Jest 或修改您的预处理器,试试 jest --no-cache.预处理器:node_modules/jest-css-modules.Jest 尝试执行以下预处理代码://some .less code

Make sure your preprocessor is set up correctly and ensure your 'preprocessorIgnorePatterns' configuration is correct: http://facebook.github.io/jest/docs/api.html#preprocessorignorepatterns-array-string If you are currently setting up Jest or modifying your preprocessor, try jest --no-cache. Preprocessor: node_modules/jest-css-modules. Jest tried to the execute the following preprocessed code: //some .less code

但是如果我注释掉 less import 行,我的测试会正确运行.

But if I comment out the less import line my test runs correctly.

我怎样才能开玩笑跳过这行代码或忽略这个导入?

How can I get jest to skip over this line of code or ignore this import?

推荐答案

除了在测试顶部手动模拟 .less 文件(例如

The only way I could get jest to ignore less files for me, other than manually mocking the .less file at the top of the test e.g.

jest.mock("../../src/styles.less", () => jest.fn());

是在 package.json 中添加以下内容:

Was to add the following to the package.json:

"jest": {
 "moduleNameMapper": {
  ".*\.less$": "<rootDir>/pathToDummyFile/dummy.js"
  }
 },

每当您的代码尝试导入较少的文件时,它都会重定向导入以获取一个空的虚拟文件,这将避免您遇到的意外令牌错误.

Whenever your code tries to import a less file it will instead redirect the import to fetch an empty dummy file, which will avoid the unexpected token error you experienced.

这篇关于测试时让 Jest 忽略 .less 导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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