您链接到的问题有一个当前已接受的答案,但不起作用。我添加了一个新答案 https://stackoverflow.com/a/55193363/10149510并附有解释和工作示例。
同样的概念也适用于此:模拟取代了模块导出一个函数以便能够模拟countriesList
within getSortedCountryData
你必须打电话给模块导出 for countriesList
.
一种选择是移动countriesList
到它自己的模块。
另一种选择是利用以下事实:“ES6 模块自动支持循环依赖” http://exploringjs.com/es6/ch_modules.html#sec_cyclic-dependencies所以这是完全有效的import
模块本身,以便您可以调用模块导出 for countriesList
:
国家.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();
});
});