我不知道如何在 jest 中模拟内部函数的返回值 我尝试了不同的方法。最后我找到了这个 answer 但出于某种原因不值得 mock ,这里是示例:
国家.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' }));
国家.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',
},
];
mockFn.spyOn(countyListHelper, 'countriesList').mockReturnValue(expectedList);
// console.log('if return value mocked correctly',
// countyListHelper.countriesList() === expectedList); // true
expect(countyListHelper.getSortedCountryData('en')).toEqual(expectedList);
// shows error with received value list of all countries instead of mocked one
});
});
请建议我任何可能的解决方案,为什么忽略内部函数的内部测试函数模拟返回值。从 Create React App 进行设置。
最佳答案
您链接到的问题当前接受的答案无效。我添加了一个 new answer带有解释和工作示例。
相同的概念适用于此:模拟替换函数的模块导出,以便能够在 getSortedCountryData
中模拟 countriesList
为 countriesList
调用模块导出。
一个选择是将 countriesList
移动到它自己的模块中。
另一种选择是利用 "ES6 modules support cyclic dependencies automatically"因此将模块import
完全有效,这样您就可以为countriesList
调用module export:
国家.js
import * as countyListHelper from './countries';
export const countriesList = () => [
{
label: '+244',
value: 'Angola',
}, // list of all possible countries very long...
];
export const getSortedCountryData = intlLang =>
countyListHelper.countriesList()
.sort((compare, comparable) =>
compare.value.localeCompare(comparable.value, intlLang, { sensitivity: 'base' }));
国家.test.js
import * as countyListHelper from './countries';
describe('countries list', () => {
test('returns list of countries', () => {
const expectedList = [
{
label: '+244',
value: 'Angola',
},
{
label: '+43',
value: 'Austria',
},
];
const spy = jest.spyOn(countyListHelper, 'countriesList');
spy.mockReturnValue(expectedList);
expect(countyListHelper.getSortedCountryData('en')).toEqual(expectedList); // Success!
spy.mockRestore();
});
});
关于javascript - 函数内部的 Jest 模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55187438/