Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.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
Javascript 如何使用配置选项测试axios_Javascript_Unit Testing_Mocking_Jestjs_Axios - Fatal编程技术网

Javascript 如何使用配置选项测试axios

Javascript 如何使用配置选项测试axios,javascript,unit-testing,mocking,jestjs,axios,Javascript,Unit Testing,Mocking,Jestjs,Axios,我正在尝试测试以下作为配置选项为put/post编写的axios请求: export function saveCourse(course){ const config = { method: course.id ? 'PUT' : 'POST',// POST for create, PUT to update when id already exists. url: baseUrl + (course.id || ''), headers: { "co

我正在尝试测试以下作为配置选项为put/post编写的axios请求:

export function saveCourse(course){
  const config = {
      method: course.id ? 'PUT' : 'POST',// POST for create, PUT to update when id already exists.
      url: baseUrl + (course.id || ''),
      headers: { "content-type": "application/json" },
      data: course
  }
  return axios(config)
  .then((res) => {
      if(res.status === 201 || res.status === 200) return res.data;
      if(res.status === 400){
          const error = res.text();
          throw new Error(error);
      }
  })
  .catch((err) => console.log(err));  
}
courseApi.test.js如下所示:

import { saveCourse } from './courseApi';
import axios from 'axios';

jest.mock('axios');

describe('check API calls', () => {
 it('should update the course', () => {
    let res = {
      id: 10,
      title: "Securing React Apps with Auth0",
      slug: "react-auth0-authentication-security",
      authorId: 2,
      category: "JavaScript"
    };

    const config = {
        method: 'put',
        url: 'http://localhost:3001/courses/10',
        headers: { "content-type": "application/json" },
        data: res
      }
    }

  axios = jest.fn().mockResolvedValue({
        status: 200,
        data: res
      });
      let result = await saveCourse(res);
      expect(result).toEqual(res);
      // expect(axiosMock.put).toHaveBeenCalledTimes(1);
 });
});
也尝试过mockImplementationOnce,在这种情况下,不会调用MockAxios

it("save course scenario", async function () {
    const course = {
      id: 10,
      title: "Securing React Apps with Auth0",
      slug: "react-auth0-authentication-security",
      authorId: 2,
      category: "JavaScript"
    };
    axios.put.mockImplementationOnce(() => Promise.resolve(course));
    expect(saveCourse(course)).resolves.toEqual(course);
    expect(axios.put).toHaveBeenCalledTimes(1);
    });
抛出错误如下:

 TypeError: Cannot read property 'then' of undefined

      24 |       data: course
      25 |   }
    > 26 |   return axios(config)
         |          ^
      27 |   .then((res) => {
      28 |       if(res.status === 201) { console.log(res); return res.data; }
      29 |       if(res.status === 200) { console.log(res); return res.data; }

      at saveCourse (src/api/courseApi.js:26:10)
      at Object.<anonymous> (src/api/courseApi.test.js:39:12)
TypeError:无法读取未定义的属性“then”
24 |数据:课程
25 |   }
>26 |返回axios(配置)
|          ^
27 |.然后((res)=>{
28 | if(res.status==201){console.log(res);返回res.data;}
29 | if(res.status==200){console.log(res);返回res.data;}
在saveCourse(src/api/courseApi.js:26:10)
at对象。(src/api/courseApi.test.js:39:12)
那么,我应该如何解决这个问题,我没有为axios mocking设置的任何东西

提前感谢!

单元测试解决方案:

index.js

从“axios”导入axios;
导出函数saveCourse(课程){
常量baseUrl=http://example.com/';
常量配置={
方法:course.id?'PUT':'POST',
url:baseUrl+(course.id | |“”),
标题:{'content-type':'application/json'},
数据:当然,
};
返回axios(配置)
。然后((res)=>{
if(res.status==201 | | res.status==200)返回res.data;
如果(资源状态===400){
常量错误=res.text();
抛出新错误(Error);
}
})
.catch((err)=>console.log(err));
}
index.test.js

从“/”导入{saveCourse};
从“axios”导入axios;
jest.mock('axios',()=>jest.fn());
描述('60992357',()=>{
之后(()=>{
开玩笑。恢复记忆();
});
它('如果状态代码等于200,则应返回数据',异步()=>{
const mRes={状态:200,数据:'假数据'};
axios.mockResolvedValueOnce(mRes);
const actual=await saveCourse({id:1});
expect(实际).toEqual(“假数据”);
期望(axios)。使用({
方法:'放',
网址:'http://example.com/1',
标题:{'content-type':'application/json'},
数据:{id:1},
});
});
它('如果状态代码等于400,则应抛出错误',异步()=>{
const mRes={status:400,text:jest.fn().mockReturnValue('network')};
axios.mockResolvedValueOnce(mRes);
constlogspy=jest.spyOn(控制台,'log');
const actual=await saveCourse({id:1});
expect(实际)。toBeUndefined();
期望(axios)。使用({
方法:'放',
网址:'http://example.com/1',
标题:{'content-type':'application/json'},
数据:{id:1},
});
expect(mRes.text).toBeCalledTimes(1);
expect(logSpy).toBeCalledWith(新错误('network');
});
});
单元测试结果和覆盖率报告:

PASS stackoverflow/60992357/index.test.js(9.916s)
60992357
✓ 如果状态代码等于200(7ms),则应返回数据
✓ 如果状态代码等于400(21ms),则应引发错误
console.log node_modules/jest environment/node_modules/jest mock/build/index.js:866
错误:网络
位于/Users/ldu020/workspace/github.com/mrdulin/react apollo graphql starter kit/stackoverflow/60992357/index.js:671:13
在进程中。_tick回调(内部/process/next_tick.js:68:7)
----------|---------|----------|---------|---------|-------------------
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s
----------|---------|----------|---------|---------|-------------------
所有文件| 100 | 70 | 100 | 100 |
index.js | 100 | 70 | 100 | 100 | 6,7,14
----------|---------|----------|---------|---------|-------------------
测试套件:1个通过,共1个
测试:2次通过,共2次
快照:共0个
时间:11.848秒

源代码:

谢谢!我错过了
async
wait
,这对我很有帮助。