从Jest中的另一个函数调用模拟函数

时间:2018-12-13 08:37:59

标签: javascript jestjs enzyme

我正在编写一个React App,我想测试我的组件是否正确获取了数据;使用笑话和酶。我想从玩笑测试中模拟的另一个函数中调用模拟的函数:

const axios = jest.mock('axios', () => {
  const mockData = {
    schools: [
      {
        id: 4,
        title: 'ABC',
        company: {
          id: 41,
          distance: '0.6 KM AWAY',
          logo: 'https://abc.xyz.jpg',
        },
        fee: 'NA',
        type: 'public',
        gender: 'Mixed',
      },
    ],
  };

  return {
    get: jest.fn(() => Promise.resolve(mockData)),
  };
});

jest.fn('getData', () => {
  axios.get();
});

const props = {
  searchResult: {
    payload: [],
    isLoading: false,
    error: {},
    searchString: '',
  },
  getData: jest.fn(axios.get()),
};

it('fetch search data on click', () => {
  const search = shallow(<SearchComponent {...props} />);
  search
    .props()
    .getData()
    .then(() => {
      expect(axios.get).toHaveBeenCalled();
      expect(axios.get).toHaveBeenCalledWith('data.json');
      expect(search.exists('search-result-card')).toBe(true);
    });
});

组件代码(只是重要的部分,因为太大而无法粘贴整个代码):

export class SearchResultComponent extends React.PureComponent {
render() {
       const { searchResult, getData } = this.props;
       <SearchInput
         placeholder="Enter keyword..."
         onClick={searchString => getData(searchString)}
       />
    }
}

运行测试时,出现此错误:

TypeError: axios.get is not a function

这有什么问题,我该如何解决?

1 个答案:

答案 0 :(得分:0)

还有其他一些问题,但我将重点回答以下问题:为什么会出现以下错误以及如何解决该问题:

TypeError: axios.get is not a function


问题

axios.get不是一个函数,因此在为props.getData创建模拟函数的实现时调用它会抛出TypeError


详细信息

jest.mock "returns the jest object for chaining"

const axios = jest.mock('axios', () => ...);axios分配给jest对象。

axios.get()运行以获取getData的{​​{1}}属性的模拟功能的实现(猜测props应该已经传递,而不是axios.get传递)

axios.get()对象不包含jest的定义,因此运行get会导致axios.get()表示TypeError


解决方案

像往常一样在测试文件的顶部导入axios.get is not a function

axios

jest.mock call gets hoisted会先运行,因此像往常一样导入import axios from 'axios';会导入模拟。

axios然后将按预期引用模拟的axios.get函数。

相关问题