繁体   English   中英

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

[英]How to assert for an error using axios and async / await

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

错误:期待(收到).rejects.toThrow()

预计收到承诺拒绝,而是决定重视
{“data”:“响应”,“状态”: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);
});

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

更新

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

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

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

...而且SpecialError可能应该将其args传递给super如下所示:

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

请注意,测试特定的错误类型消息有点棘手,因为toThrow允许您检查一个或另一个,但不能同时检查两个。 你可以通过逐个测试来解决这个限制。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM