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

Jim*_*mmy 7 javascript async-await jestjs axios

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

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

预期收到Promise拒绝,而是解析为值
{“ 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;
Run Code Online (Sandbox Code Playgroud)

specialError.js:

export default class SpecialError extends Error {
  constructor() {
    super();
    this.isSpecialError = true;
  }
}
Run Code Online (Sandbox Code Playgroud)

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);
});
Run Code Online (Sandbox Code Playgroud)

Bri*_*ams 6

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!
});
Run Code Online (Sandbox Code Playgroud)

更新

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

你可能想抛出这样的错误:

try {
  // ...
} catch (error) {
  throw new SpecialError(error.message);  // <= just use the error message
}
Run Code Online (Sandbox Code Playgroud)

...并且SpecialError应该super像这样传递它的参数:

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

...但考虑到这些变化,你可以这样测试:

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
});
Run Code Online (Sandbox Code Playgroud)

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