用Jest测试module.hot [英] Test module.hot with Jest

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

问题描述

我正在尝试使用热模块重新加载设置将模块的覆盖率提高到100%.

I'm trying to get coverage to 100% for a module with hot module reloading setup.

在我的模块中,我有这个:

In my module I have this:

// app.js
if (module && module.hot) module.hot.accept();

在测试文件中,我正在尝试这样做

In the test file I am trying to do this

// app.test.js
it('should only call module.hot.accept() if hot is defined', () => {
    const accept = jest.fn();
    global.module = { hot: { accept } };
    jest.resetModules();
    require('./app');
    expect(accept).toHaveBeenCalled();
  }
);

但是当我在app.js中注销模块时,它显示了必填内容,但不包含测试设置的热门方法.

But when I log out module in app.js it shows the require stuff but doesn't contain the hot method set by test.

推荐答案

我也需要它,而不能从外部传递它.

I've needed it as well without the ability to pass it from outside.

我的解决方案是使用一个开玩笑的"transform" 允许我稍微修改使用module.hot的文件的代码.

My solution was to use a jest "transform" that allows me to modify a bit the code of the file that is using module.hot.

因此,要进行设置,您需要添加:

So in order to setup it you need to add:

// package.json

"transform": {
  "file-to-transform.js": "<rootDir>/preprocessor.js"
//-------^ can be .* to catch all
//------------------------------------^ this is a path to the transformer
},

preprocessor.js内部,

// preprocessor.js

module.exports = {
  process(src, path) {
    if( path.includes(... the path of the file that uses module.hot)) {
      return src.replace('module.hot', 'global.module.hot');
    }

    return src;
  },
};

该变压器会将module.hot替换为global.module.hot,这意味着您可以在如下测试中控制其值:

That transformer will replace module.hot to global.module.hot, that means that you can control it value in the tests like so:

// some-test.spec.js

global.module = {
  hot: {
    accept: jest.fn,
  },
};

希望有帮助.

这篇关于用Jest测试module.hot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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