[英]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()
运行以获取props
的getData
属性的模拟功能的实现(猜测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.