I have created a working Mock for Axios:
// __mocks__/axios.js
// Based on https://jestjs.io/docs/manual-mocks
const axios = jest.createMockFromModule("axios");
const log = console.log.bind(console);
axios.create = () => {
log(`Running axios.create`);
return {
get: () => {
log(`Running get`);
return {
status: 500,
statusText: "Internal Server Error",
body: {
onFire: "Mock API response from mock axios module",
},
};
},
};
};
module.exports = axios;
This works fine in my tests - the mock is loaded automatically and the 'throws an error' test works:
describe(`getLatestPrice`, () => {
it(`throws an error when the response is bad`, async () => {
expect(() => {
log(`Should throw`);
return getLatestPrice(assetCode);
}).toThrow();
});
it(`gets a single price by stream code`, async () => {
// Disabling the mock isn't working
jest.unmock("axios");
const price = await getLatestPrice(assetCode);
log(`price`, price);
expect(price).toEqual({
...
});
});
})
However the second test - which calls jest.unmock() - still uses the mocked library.
How can I disable mocking for a single test?
Update: reading https://github.com/facebook/jest/issues/2649 I've also tried using requireActual() to override the mock:
const actualAxios = jest.requireActual("axios");
const mockAxios = require("axios");
mockAxios.create = actualAxios.create;
But calls to axios.create() still invole the mock.