我正在编写一个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
这有什么问题,我该如何解决?
答案 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
函数。