繁体   English   中英

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

[英]Call mocked function from another function in Jest

我正在编写一个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

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

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

TypeError: axios.get is not a function


问题

axios.get不是创建模拟功能的实现时,那么调用它的功能props.getData抛出一个TypeError


细节

jest.mock “返回链接的jest对象”

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

axios.get()运行以获取propsgetData属性的模拟功能的实现(猜测axios.get应该已传递,而不是axios.get() )。

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


axios一样在测试文件的顶部导入axios

import axios from 'axios';

jest.mock调用被挂起并首先运行,因此,像正常axios一样导入axios将导入该模拟。

然后, axios.get将按预期引用axios.get get函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM