本文介绍了在测试中替换特定模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jest测试我的React-Redux应用程序,并且在我的API调用中,我正在导入一个获取模块 cross-fetch 。我想用 fetch-mock 覆盖或替换它。这是我的文件结构:

I am testing my React-Redux app with Jest and as part of this in my API calls I am importing a fetch module cross-fetch. I want to override or replace this with fetch-mock. Here is my file structure:

Action.js

import fetch from 'cross-fetch';
export const apiCall = () => {
    return fetch('http://url');

Action.test.js

import fetchMock from 'fetch-mock';
import { apiCall } from './Action';
fetchMock.get('*', { hello: 'world' });
describe('actions', () => {
    apiCall().then(
        response => {
            console.log(response)
        })
})

显然此时我还没有设置测试。因为交叉获取是在更接近函数的情况下导入的,所以它使用fetch的实现,导致它执行实际调用而不是我的模拟。什么是获取模拟的最佳方法(除了从'cross-fetch'行中删除 import fetch)?

Obviously at this point I haven't set up the test. Because cross-fetch is imported closer to the function it uses it's implementation of fetch, causing it to do the actual call instead of my mock. Whats the best way of getting the fetch to be mocked (apart from removing the import fetch from 'cross-fetch' line)?

是否有办法进行条件导入,具体取决于调用的节点脚本是 test 还是 build ?或者将模拟的提取设置为优先级?

Is there a way to do a conditional import depending on whether the node script called is test or build? Or set the mocked fetch to take priority?

推荐答案

如果您的项目是webpack项目,那么非常有用。你可以在几行代码中简单地用模拟交换任何依赖。

If your project is a webpack project, then https://github.com/plasticine/inject-loader is very useful. You can simply swap any dependency with a mock in just a few lines of code.

describe('MyModule', () => {
  let myModule;
  let dependencySpy;

  beforeEach(() => {
    dependencySpy= // {a mock/spy};
    myModule = require('inject-loader!./MyModule')({
      'cross-fetch': {dependencySpy},
    });
  });

  it('should call fetch', () => {
    myModule.function1();
    expect(dependencySpy.calls.length).toBe(1);
  });

});

注意:确保不要导入文件顶部的测试模块。 要求调用该部分。

Note: make sure you don't import the module under test at the top of your file. the require call does that part.

这篇关于在测试中替换特定模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 14:35