Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何使用Jest为componentDidMount上的API调用编写测试用例_Reactjs_Jestjs_Enzyme - Fatal编程技术网

Reactjs 如何使用Jest为componentDidMount上的API调用编写测试用例

Reactjs 如何使用Jest为componentDidMount上的API调用编写测试用例,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,我想为componentDidMount上的await API调用编写一个测试用例,以获得成功和错误 我添加了API调用的行为代码,请建议测试用例实现 从“/../../../../../\u服务”导入{apiService} 从“react”导入{Component}; 类MyComponent扩展组件{ 建造师(道具){ 超级(道具); 此.state={ contentId:123, 用户ID:1345 }; } componentDidMount(){ this.getMappedCon

我想为componentDidMount上的await API调用编写一个测试用例,以获得成功和错误

我添加了API调用的行为代码,请建议测试用例实现

从“/../../../../../\u服务”导入{apiService}
从“react”导入{Component};
类MyComponent扩展组件{
建造师(道具){
超级(道具);
此.state={
contentId:123,
用户ID:1345
};
}
componentDidMount(){
this.getMappedContent()的
。然后(内容=>{
如果(内容){
if(content.contentData&&content.contentData.isLocked){
if(content.contentData.lockedByEmail!==this.state.userID){
this.setState({isLocked,lockedBy})
}
}
this.setState({users:content.contentData})
}
})
.catch(错误=>{
})
}
getMappedContent=async()=>{
如果(!this.state.contentId){
返回;
}
常量requestParams={
contentId:this.state.contentId,
};
//获取现有的mapContent项(如果存在)
return wait apiService.getUser(requestParams);
};
}
//apiService.js 这是我的API服务代码,请建议我写一个测试用例,以防成功和失败

import Config from "./config";
import axiosInstance from "./axiosInstancs";

    const getUser = (params) => {
     const query = createQuery(params);
     const url = `${Config.users}${query ? query : ''}`
       return axiosInstance.get(url)
        .then(response => {
           return response.data.data;
         })
        .catch(error => {
          return false;
       });
    }
export const apiService = {
  getUser
}
在这里,我试图写一个成功和失败的测试用例,请建议我在这方面还可以改进什么

it('Should success API call with contentId', async () => {
        const expectedPosts = [
          {id: 1, title: 'test1'},
          {id: 2, title: 'test2'},
        ]
        const mock = jest.fn().mockReturnValue(expectedPosts);
        apiService.getUser = mock;
        const result = await apiService.getUser({contentId: 134});
        expect(result).toBe(expectedPosts);
     })

     it('Should not success API call without contentId', async () => {
        const expectedPosts = []
        const mock = jest.fn().mockReturnValue(expectedPosts);
        apiService.getUser = mock;
        const result = await apiService.getUser({});
        expect(result).toBe(expectedPosts);
     })