函数内的 Jest 模拟函数

Yar*_*niy 9 javascript jestjs create-react-app

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

国家.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',
      },
    ];

    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
  });
});
Run Code Online (Sandbox Code Playgroud)

请向我建议任何可能的解决方案,为什么忽略内部函数的内部测试函数模拟返回值。从 Create React App 设置。

Bri*_*ams 13

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

同样的概念也适用于这里:一个模拟替换模块导出功能,这样才能够嘲笑countriesList之内getSortedCountryData你要调用的模块出口countriesList

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

另一种选择是采取的这一事实的优点“ES6模块自动支持循环依赖”所以它是完全有效的import模块到自身,这样就可以调用模块导出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' }));
Run Code Online (Sandbox Code Playgroud)

国家.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();
  });
});
Run Code Online (Sandbox Code Playgroud)