简体   繁体   中英

How to Mock HTTP404 with axios-mock-adapter and custom error object

I have an overridden Axios function which helps me make API requests. the implementation of that function is that when the API call fails, it adds attributes in error.customAttributes .

try {
   const data = await getMeDataPlease(param);
} catch (error) {
  if (error.customAttributes.httpErrorStatus === 404) {
    error.userError = {} // anything
    throw error;
  }
}

I would like to test this function catch code, that it correctly adds/builds error.userError object. for that, I am mocking Axios call as following.

describe('External Apis', () => {
  it('Get me data fails', async () => {
    const axiosMock = new MockAdapter(myCustomHttpClient());
    const url = 'my-data-url-goes-here';

    axiosMock.onGet(url).reply(404, {customAttributes: {httpErrorStatus:404});
    const data = await getEnrollments('username'); // in actual method the method fails on `if (error.customAttributes.httpErrorStatus === 404)` with undefined does not have `httpErrorStatus`
    console.log('data', data);
  });

but I am not able to mock Axios request like that, the error object does not contain my expected customAttributes . Kindly advise.

I'm having the same issue, and the workaround I found is to mock with rejected promise:

 mock.onGet(url).reply(() => Promise.reject({ customAttributes: {httpErrorStatus:404} }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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