我有以下模块我试图在Jest中测试:
// myModule.js
export function otherFn() {
console.log('do something');
}
export function testFn() {
otherFn();
// do other things
}
Run Code Online (Sandbox Code Playgroud)
如上图所示,这部分出口命名的功能和重要的testFn用途otherFn.
在Jest中我正在编写单元测试时testFn,我想模拟该otherFn函数,因为我不希望错误otherFn影响我的单元测试testFn.我的问题是我不确定最好的方法:
// myModule.test.js
jest.unmock('myModule');
import { testFn, otherFn } from 'myModule';
describe('test category', () => {
it('tests something about testFn', () => {
// I want to mock "otherFn" here but can't reassign
// a.k.a. can't do otherFn = jest.fn()
});
});
Run Code Online (Sandbox Code Playgroud)
任何帮助/见解表示赞赏.
我有一个名为helper.js的文件,其中包含两个函数
export const funcA = (key) => {
return funcB(key)
};
export const funcB = (key,prop) => {
return someObj;
};
Run Code Online (Sandbox Code Playgroud)
我有我的helper.spec.js来测试helper.js文件的功能。
import {funcA,funcB} from 'helper';
describe('helper', () => {
test('testFuncB', () => {
}
test('testFuncA', () => {
}
}
Run Code Online (Sandbox Code Playgroud)
对funcB的测试非常简单,我只调用它并期望someObj
。问题是测试funcA,为了对其进行测试,我想模拟funcB的响应。
我希望testFuncB调用实际的funcB,而testFuncA调用模拟的funcB
我如何在两个测试中实现对funcB的模拟和原创?
这不是重复项。这是不同的情况:它们仅模拟内部调用的函数,如果我删除了testFuncB,那将是相同的,但是我也必须对testFuncB进行测试。
我不知道如何在玩笑中模拟内部函数的返回值我尝试了不同的方法。最后我找到了这个答案, 但由于某种原因不值得嘲笑,这是示例:
国家.js
export const countryList = () => [
{
label: '+244',
value: 'Angola',
}, // list of all possible countries very long...
];
export const getSortedCountryData = intlLang =>
countriesList()
.sort((compare, comparable) =>
compare.value.localeCompare(comparable.value, intlLang, { sensitivity: 'base' }));
Run Code Online (Sandbox Code Playgroud)
国家.test.js
import * as countyListHelper from './countries';
describe('countries list', () => {
test('returns list of countries', () => {
const mockFn = jest.mock();
const expectedList = [
{
label: '+244',
value: 'Angola',
},
{
label: '+43',
value: 'Austria', …Run Code Online (Sandbox Code Playgroud)