在函数内部开玩笑

时间:2019-03-15 16:58:42

标签: javascript jestjs create-react-app

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

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

请提出任何可能的解决方案,为什么忽略内部测试函数的内部函数模拟返回值。通过Create React App进行设置。

1 个答案:

答案 0 :(得分:1)

您链接到的问题的答案当前无效。我添加了一个new answer并带有说明和有效示例。

此处使用相同的概念:模拟代替函数的模块导出,因此要在countriesList中模拟getSortedCountryData,您必须调用 countriesList的模块导出

一种选择是将countriesList移到其自己的模块中。

另一种选择是利用"ES6 modules support cyclic dependencies automatically"这一事实,因此将import模块插入自身是完全有效的,这样您就可以调用 module export 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();
  });
});