1

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.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
A.J.
  • 8,557
  • 11
  • 61
  • 89
  • Can you share your full test file? – tmhao2005 Nov 07 '20 at 09:56
  • Sure. i have upded the file. – A.J. Nov 07 '20 at 10:32
  • Cool. Can you also share your custom http and the way you import it into the actual file and test file as well? Since you might have had 2 instances of http object – tmhao2005 Nov 07 '20 at 10:38
  • https://github.com/edx/frontend-platform/tree/master/src/auth – A.J. Nov 07 '20 at 16:10
  • Not sure where exactly your code is but the test in the dir is now set up right by sharing the same `axios` instance between the service and the test (passing the http instance which is being used in the service to `MockAdapter` in test) – tmhao2005 Nov 07 '20 at 17:38

1 Answers1

0

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}
}));
Sava Jcript
  • 384
  • 2
  • 5