Unit testing interceptors

See original GitHub issue

So, I have added this response interceptor that would basically just clear out the localstorage items if the status is 401. I haven’t have found luck with unit testing it:

axios.interceptors.response.use((response) => {
  if (response.status === 401) {
    storage.clear();
  }
  return response;
});

I have tried moxios but haven’t been lucky with it when it comes to interceptors.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:14 (2 by maintainers)

github_iconTop GitHub Comments

45reactions
lmamminocommented, Jul 24, 2017

To be more specific, if I have the following interceptor:

const instance = axios.create()
instance.interceptors.response.use(
  response => response.data,
  err => {
    const error = new Error(err.response.statusText)
    error.statusCode = err.response.status
    error.data = err.response.data
    return Promise.reject(error)
  }
)

This is how I test it with jest:

expect(client.interceptors.response.handlers[0].fulfilled({data: 'foo'})).toBe('foo')

expect(client.interceptors.response.handlers[0].rejected({
  response: {
    statusText: 'NotFound',
    status: 404,
    data: {message: 'Page not found'}
  }
})).rejects.toMatchObject({
  message: 'NotFound',
  statusCode: 404,
  data: {message: 'Page not found'}
})

I hope this is still useful, even if the original issue is dated almost a year ago 😃

6reactions
m-sureshrajcommented, Mar 7, 2019

Hi @okovalov, I think the issue is because of mocking axios module.

with mocking

jest.mock('axios');
console.log(axios.interceptors.response.handlers);

output:

image

without mocking

console.log(axios.interceptors.response.handlers);

output:

image

here is the working example

// interceptors.js
import axios from 'axios';

export function initUnauthorizedResponseInterceptor() {
    axios.interceptors.response.use(
        res => res,
        error => {
            if (error.response.status === 403) {
                window.location.replace('/login');
                return;
            }

            return Promise.reject(error);
        },
    );
}
// interceptors.spec.js
import axios from 'axios';
import * as interceptor from '../interceptors';

describe('Interceptors', () => {
    describe('initUnauthorizedResponseInterceptor', () => {
        interceptor.initUnauthorizedResponseInterceptor();

        it('should throw error if response status is other then 403', () => {
            const res = {
                response: { status: 401 },
            };
            const rejectedRes = axios.interceptors.response.handlers[0].rejected(res);

            expect(rejectedRes).rejects.toMatchObject(res);
        });

        it('it should redirect to login page if response status is 403', () => {
            // global is `window` in jest
            global.location.replace = jest.fn();

            const rejectedRes = axios.interceptors.response.handlers[0].rejected({
                response: { status: 403 },
            });

            expect(global.location.replace).toBeCalledWith('/login');
            expect(rejectedRes).toBeUndefined();
        });
    });
});

cc - @rs-8

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to unit test an HTTP interceptor in Angular using Jasmine
How to unit test an HTTP interceptor in Angular using Jasmine · Execute request using httpMock and inspect actual request/response. angular.io/ ...
Read more >
How to write Unit Test Cases for Angular HTTP Interceptor
In this article we are going write unit test cases for an interceptor (HttpConfigInterceptor) which will add required header configuration to ...
Read more >
How to Test Angular Response Interceptors - Embrace IT
Testing Angular interceptors is easy - once you know how. Find out everything you need to start unit testing your interceptors right away....
Read more >
How to test a http interceptor in Angular application - ng-mocks
To test an interceptor we need the interceptor itself and its module. Please consider refactoring if the interceptor is defined by useValue ...
Read more >
Ngx Unit Test Interceptor - StackBlitz
unit -test with interceptor.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found