【发布时间】:2018-09-24 02:33:34
【问题描述】:
您能否告诉我如何使用enzyme 测试componentDidMount 函数。我正在从componentDidMount 中的服务器获取数据,它工作得很好。现在我想测试这个函数。
这是我的代码 https://codesandbox.io/s/oq7kwzrnj5
componentDidMount(){
axios
.get('https://*******/getlist')
.then(res => {
this.setState({
items : res.data.data
})
})
.catch(err => console.log(err))
}
我试试这样
it("check ajax call", () => {
const componentDidMountSpy = jest.spyOn(List.prototype, 'componentDidMount');
const wrapper = shallow(<List />);
});
查看更新的代码
https://codesandbox.io/s/oq7kwzrnj5
it("check ajax call", () => {
jest.mock('axios', () => {
const exampleArticles:any = {
data :{
data:['A','B','c']
}
}
return {
get: jest.fn(() => Promise.resolve(exampleArticles)),
};
});
expect(axios.get).toHaveBeenCalled();
});
【问题讨论】:
-
为了测试 react 将调用 componentDidMount 正在测试库内部。没有必要这样做。我认为您想测试 axios 是否已执行。
-
@TomaszMularczyk 是的,我会怎么做
-
@TomaszMularczyk 你能帮我看看我将如何测试axis.get方法
标签: javascript reactjs unit-testing react-redux enzyme