函数内部的 Jest 模拟函数

Jest mock function inside function

我不知道如何在 jest 中模拟 return 内部函数的值 我尝试了不同的方法。最后我找到了这个 但由于某种原因不值得嘲笑,这里是示例:

countries.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' }));

countries.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
  });
});

请建议我任何可能的解决方案,为什么内部测试函数 mocked return 内部函数的值被忽略。从 Create React App 进行设置。

您链接到的问题当前接受的答案无效。我添加了一个带有解释和工作示例的

相同的概念适用于此:模拟替换函数的 模块导出 ,因此要能够在 getSortedCountryData 中模拟 countriesList,您必须为 countriesList.

调用 模块导出

一种选择是将 countriesList 移动到它自己的模块。

另一种选择是利用 "ES6 modules support cyclic dependencies automatically" 这一事实,因此 import 模块完全有效,这样您就可以调用 模块导出 对于 countriesList:

countries.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' }));

countries.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();
  });
});