在 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
是一些复杂的函数.我如何测试这个,并且不受 fetchResourceFromBackend
代码的影响(任何模式或工具推荐,我使用 mocha
和 sinon
但无法实现)?
fetchResourceFromBackend
is some complicated function. 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
作为参数提供给 fetchSomething
是我唯一的选择吗?
Is my only option to provide fetchResourceFromBackend
as an argument to fetchSomething
so I can mock it?
推荐答案
Using jest 正如@Mikhail 建议的那样,我是这样解决的:
Using jest as @Mikhail suggested I solved like this:
// test/something-test.js
import {myFetch} from '../_mocks_/utilities';
jest.doMock('modules/utilities', () =>({
myFetch: myFetch
}));
const {fetchSomething} = require('modules/something');
describe('#fetchSomething', ...
这里的 fetchSomething
是被测试的函数,它内部依赖于 'modules/utilities'
中的 myFetch
函数.我用 '../_mocks_/utilities'
中的 myFetch
来模拟这种依赖.
Here fetchSomething
is function under test that has internal dependency on myFetch
function from 'modules/utilities'
. I mock that dependency with myFetch
from '../_mocks_/utilities'
.
这篇关于在 Javascript 中模拟被测模块/函数的依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!