knee-cola / jest-mock-axios

Axios mock for Jest
252 stars 42 forks source link

mock axios using axios interceptors #23

Closed DatVuGcc closed 5 years ago

DatVuGcc commented 5 years ago

I'm trying to use mockAxios for testing with axios interceptors.

image

image

When I created mockAxios: export default { get: jest.fn(() => Promise.resolve(data: {})) } All of my tests failed with the follow message: cannot read property response of undefined inside of axios interceptors. It happens because mock axios doesn't return response. It could just return a plain object. So how can I use axios interceptors with mockAxios for testing? image

marvinkome commented 5 years ago

I used this in my __mocks__/axios.js file:


import mockAxios from 'jest-mock-axios';
export default {
    ...mockAxios,
    create: jest.fn(() => ({
        ...mockAxios,
        defaults: {
            headers: {
                common: {}
            }
        },
        interceptors: {
            request: {
                use: jest.fn()
            },
            response: {
                use: jest.fn()
            }
        }
    }))
};```
chimilord commented 5 years ago

@marvinkome works smooth! Thanks.

DatVuGcc commented 5 years ago
import mockAxios from 'jest-mock-axios';
export default {
    ...mockAxios,
    create: jest.fn(() => ({
        ...mockAxios,
        defaults: {
            headers: {
                common: {}
            }
        },
        interceptors: {
            request: {
                use: jest.fn()
            },
            response: {
                use: jest.fn()
            }
        }
    }))
};

Didn't help. Still have the same issue.

kingjan1999 commented 5 years ago

That's a duplicate of #5.