简体   繁体   English

如何模拟和测试 Axios 拒绝 promise?

[英]How to mock and test Axios rejected promise?

I created a class called API and it's a simple wrapper around Axios我创建了一个名为 API 的 class ,它是 Axios 的简单包装器

export class API {    
  static get = async (route: string, version: string = API_VERSION) => {
    try {
      return await axios.get(`${BASE_URL + version}${route}`);
    } catch (error) {
      throw error;
    }
  };
}

I'm trying to test the catch branch of the get method:我正在尝试测试 get 方法的 catch 分支:

I tried:我试过了:

describe('API Throws Errors', () => {
  beforeEach(() => {
    // axios.get.mockImplementation(() => Promise.reject('rejected'));
    jest.mock('axios', () => ({
      get: jest.fn().mockReturnValue(Promise.reject('error'))
    }));
  });

  it('get fails', async () => {
    await expect(() => {
      API.get(GROUPS.url());
    }).rejects.toEqual('error');
  });

  afterEach(() => {
    jest.clearAllMocks();
  });
});

在此处输入图像描述

You can mock behaviour of axios.get by using jest.mock .您可以使用jest.mock模拟axios.get的行为。 Put the below code above the describe section:将以下代码放在describe部分上方:

jest.mock('axios', () => ({
  get: jest.fn().mockReturnValue(Promise.reject('error'))
}));

And you test the error like below:然后您测试如下错误:

it('get fails', async () => {
    await expect(API.get("bad_url")).rejects.toEqual('error');
});

Exact Code确切的代码

jest.mock('axios', () => ({
    get: jest.fn().mockReturnValue(Promise.reject('error')),
}));

describe('API Throws Errors', () => {
    it('get fails', async () => {
        await expect(API.get(GROUPS.url())).rejects.toEqual('error');
    });
});

Note :注意

If you have another test case that shouldnt be failed, you can just mock it to return Promise.resolve() .如果您有另一个不应该失败的测试用例,您可以模拟它以返回Promise.resolve() Or you can just simple clear the mock.或者你可以简单地清除模拟。

describe('API Throws Errors', () => {
    it('get fails', async () => {
        await expect(API.get(GROUPS.url())).rejects.toEqual('error');
    });
    
    it('should success', async () => {
        Axios.get.mockReturnValue(Promise.resolve(SOME_VALUE));
        await expect(API.get(GROUPS.url())).resolves.toEqual(SOME_VALUE);
    });
});

toThrowError() is supposed to be asserted against a function and not result because if an error happens on function call, expect doesn't have a chance to be evaluated. toThrowError()应该针对 function 断言而不是结果,因为如果 function 调用发生错误,则expect没有机会进行评估。 It's applicable only to regular functions where an error is thrown.它仅适用于抛出错误的常规函数。 It's not applicable to async functions because they don't throw an error but return a result, which rejected promise.它不适用于async函数,因为它们不会抛出错误而是返回结果,该结果拒绝了 promise。

rejects.toThrowError() construction is a way how rejected promise can be asserted, an assertion needs to be provided with a promise instead of a function that returns it: rejects.toThrowError()构造是一种方式拒绝 promise 可以被断言,断言需要提供 promise 而不是 function 返回它:

await expect(API.get("bad_url")).rejects.toThrowError();

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

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