如何使用axios和async / await声明错误

时间:2019-05-30 23:25:34

标签: javascript async-await jestjs axios

我正在尝试编写一个断言使用Async / Await和axios引发特定类型错误的测试。但是,当我运行测试时,得到以下信息。为什么开玩笑不能正确地拒绝我的承诺?谢谢!

  

错误:expect(receives).rejects.toThrow()

     

预期收到的Promise会被拒绝,而是决定为值
  {“数据”:“响应”,“状态”:404}

api.js:

import axios from 'axios';
import SpecialError from './specialError.js';

const get = async () => {
  try {
    const response = await axios.get('sampleUrl', { withCredentials: true });
    return response;
  } catch (error) {
    throw new SpecialError(error);
  }
};

export default get;

specialError.js:

export default class SpecialError extends Error {
  constructor() {
    super();
    this.isSpecialError = true;
  }
}

api.test.js:

import axios from 'axios';
import get from './api';
import SpecialError from './specialError.js';

test('testing the api get method', async () => {
  axios.get.mockImplementation(() => Promise.resolve({
    data: 'response',
    status: 404,
  }));

  const expectedError = new SpecialError('foo');

  await expect(get()).rejects.toEqual(expectedError);
});

1 个答案:

答案 0 :(得分:1)

axios.get被模拟为解析为一个对象,因此get解析为该对象。

您似乎正在测试错误情况,在这种情况下,axios.get应该被模拟为拒绝:

import axios from 'axios';
import get from './code';

test('testing the api get method', async () => {
  jest.spyOn(axios, 'get').mockRejectedValue(new Error('error'));
  await expect(get()).rejects.toThrow('error');  // Success!
});