webpack在玩笑单元测试中需要非js内容 [英] webpack require non-js content in jest unit-tests

查看:344
本文介绍了webpack在玩笑单元测试中需要非js内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我已经将我的一个项目转换为webpack&通天塔它是由剔除组件制成的.

Recently I've converted one of my projects to webpack & babel. It is made out of knockout components.

运行单元测试时遇到问题.如果我在 tests 文件夹中有一个文件,例如

I'm running into a problem while running the unit-tests. If I have a file in the tests folder like

import component from '../custom-options';

test('adds 1 + 2 to equal 3', () => {
  expect(3).toBe(3);
});

问题在于该组件是一个需要排序的模块

The problem is that the component is a module which has a require of the sort

var htmlString = require('./custom-options.html');

当我尝试运行网站本身时,它运行正常,因为针对此需求配置了原始加载程序.但是,当我开玩笑地测试输出时:

When I try to run the website itself it runs fine, as the raw loader is configured for this require. However, when I run jest the test outputs:

 custom-options.html:1
 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){?<div id="custom-options-containe" class="mod--custom-options">
                                                                                          ^
SyntaxError: Unexpected token <

  at transformAndBuildScript (node_modules\jest-cli\node_modules\jest-runtime\build\transform.js:284:10)
  at custom-options.js:13:38
  at Object.<anonymous> (custom-options.js:93:3)

知道为什么会这样吗?我以为开玩笑是有错的,但是我尝试用Ava消除它,结果是一样的.我开始认为这是通天塔的问题.

Any idea why this is happening? I thought jest was at fault but I've tried subbing it out with Ava and the result is the same. I'm beginning to think it's a babel problem.

我正在用babel-jest预处理程序来开玩笑.

I'm running jest with the babel-jest preprocessor.

推荐答案

您可以在package.json的jest设置中为所有没有JS文件创建全局模拟,如下所示:

You can create a global mock for all none JS files in you jest settings in the package.json like this:

"jest": {
  "moduleNameMapper": {
    "^.+\\.html$": "<rootDir>/__mocks__/htmlMock.js"
  }
}

然后在项目根目录的__mocks__文件夹中创建文件htmlMock.js,其内容如下:

then create the file htmlMock.js in the __mocks__ folder in your project root with the following content:

module.exports = 'test-file-stub';

有关更多信息,请此处

如果您希望每个测试用例都有一个特殊的模拟,您也可以像这样在测试中模拟文件:

If you want do have a special mock for every test case you can also mock the file in your test like this:

jest.mock('path/from/test/to/custom-options.html', ()=> 'test-file-stub');

请注意,该路径是相对于测试文件而言的,而不是相对于您要测试的文件而言的.

Notice that the path is relative to the test file not to the file you want to test.

这篇关于webpack在玩笑单元测试中需要非js内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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