我正在使用jest进行反应原生的单元测试。这是我的componentWillMount()函数:
componentWillMount() {
this.setState({ loading: true });
axios.get(SERVER_URL + '/courses')
.then(response => {
this.state.trainingcatalogues = []
this.state.traininglist = []
this.state.Location1 = []
this.state.Category1 = []
this.state.Location2 = ['All']
this.state.Category2 = ['All']
for (var key in response.data) {
if (response.data[key].coursetype === 'Instructor-Led' && response.data[key].status === 'Active' ) {
this.state.Location1.push(response.data[key].location);
this.state.Category1.push(response.data[key].category);
this.state.trainingcatalogues.push(response.data[key]);
this.state.traininglist.push(response.data[key]);
}
}
我想嘲笑回复'在我的测试用例中。它具有以下格式:
let response =
{
"data": [
{
"_id": "5acb16701e09ae8abc29e7fb",
"courseName": "Agile Fundamentals420",
"category": "Agile",
"coursetype": "Instructor-Led",
"duration": 22,
"addnote": "contractor",
"status": "Completed",
"registrations": 10
}
]
}
这是我的单元测试用例:
it('should test the componentwillMount function', () => {
const wrapper = shallow(<Instructor_cata navigation = {navigation}/>);
const instance = wrapper.instance();
const componentWillMountSpy = jest.spyOn(instance,"componentWillMount");
instance.forceUpdate();
instance.componentWillMount();
expect(componentWillMountSpy).toHaveBeenCalled();
});
如何在单元测试用例中模拟此响应数据?
答案 0 :(得分:0)
您需要模拟Axios库,并且有几个选项可以执行此操作。首先有一些像axios-mock-adapter或jest-mock-axios这样的库,但是你自己也可以自己编写一个模拟器,它没什么用。
基本示例:
// mock.js: custom axios mock file in your tests folder
module.exports = {
get: jest.fn((url) => {
switch (url): {
case '<your_url>/courses':
return Promise.resolve(<your_response_object>)
default:
return Promise.resolve({...})
})
}
};
只需在测试文件中导入模拟。并且您可以对post()等其他axios方法使用类似的方法。