提问者:小点点

如何使用axios和async/await断言错误


我正在尝试编写一个测试,它断言用Async/Await和Axios抛出了特定类型的错误。但是,当我运行我的测试时,我得到以下结果。为什么jest不恰当地拒绝我的承诺?谢啦!

错误:expect(received).Rejects.ToThrow()

预期已收到拒绝承诺,但它解析为ValueBR>Data":“Response",”Status":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个答案

匿名用户

被模拟以解析为对象,因此解析为该对象。

看起来您正在测试错误案例,在这种情况下,应该被嘲弄以拒绝:

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!
});

更新

OP更新了问题,询问如何测试特定类型的错误。

您可能希望抛出如下所示的错误:

try {
  // ...
} catch (error) {
  throw new SpecialError(error.message);  // <= just use the error message
}

。。。和可能应该将其参数传递给,如下所示:

export default class SpecialError extends Error {
  constructor(...args) {
    super(...args);  // <= pass args to super
    this.isSpecialError = true;
  }
}

。。。但是考虑到这些变化,您可以这样测试:

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

test('testing the api get method', async () => {
  jest.spyOn(axios, 'get').mockRejectedValue(new Error('the error'));
  const promise = get();
  await expect(promise).rejects.toThrow(SpecialError);  // <= throws a SpecialError...
  await expect(promise).rejects.toThrow('the error');  // <= ...with the correct message
});

请注意,测试特定的错误类型和消息有点棘手,因为允许您检查其中一种,但不能同时检查两者。您可以通过对每一个单独进行测试来绕过这个限制。