简体   繁体   English

Javascript中受测试模块/功能的模拟依赖

[英]Mocking dependency of module/function under test in Javascript

Let's say I want to test the following for example: 假设我要测试以下示例:

import {fetchResourceFromBackend} from './myfetch';

const fetchSomething = (dispatch) => {

  dispatch(2);

  return fetchResourceFromBackend('/api/abc').then( result => {
    dispatch(3);
  });
};

fetchResourceFromBackend is some complicated function. fetchResourceFromBackend是一些复杂的函数。 How can I test this, and not be affected by fetchResourceFromBackend code (any pattern or tool recommendations, I use mocha and sinon but cannot achieve)? 我该如何进行测试,并且不受fetchResourceFromBackend代码的影响(任何模式或工具建议,我都使用mochasinon但无法实现)?

Is my only option to provide fetchResourceFromBackend as an argument to fetchSomething so I can mock it? 是我提供的唯一选择fetchResourceFromBackend作为参数传递给fetchSomething ,所以我可以嘲笑它?

Using jest as @Mikhail suggested I solved like this: 使用笑话作为@Mikhail建议我这样解决:

// test/something-test.js

import {myFetch} from '../_mocks_/utilities';

jest.doMock('modules/utilities', () =>({
    myFetch: myFetch
}));


const {fetchSomething} = require('modules/something');

describe('#fetchSomething', ...

Here fetchSomething is function under test that has internal dependency on myFetch function from 'modules/utilities' . 这里的fetchSomething是受测试的函数,它与'modules/utilities' myFetch函数有内部依赖性。 I mock that dependency with myFetch from '../_mocks_/utilities' . 我从'../_mocks_/utilities'myFetch模拟了这种依赖关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM