I'm trying to unit test componentDidMount
while mocking an Axios call.
// src/App.tsx
import axios_with_baseUrl from './axios-instance-with-baseUrl';
...
public componentDidMount() {
axios_with_baseUrl.get('/data.json')
.then(resp => this.setState({ stuff }));
}
// src/App.test.tsx
jest.mock('./axios-instance-with-baseUrl', () => {
return {
get: jest.fn(() => Promise.resolve(someFakeData))
};
});
import axios_with_baseUrl from './axios-instance-with-baseUrl';
test('fetches data on componentDidMount', async () => {
const app = enzyme.shallow(<App />);
app.instance().componentDidMount()
.then(() => {
expect(axios_with_baseUrl.get).toHaveBeenCalled();
});
});
When I test the above code, I get the following error message:
TypeError: Cannot read property 'then' of undefined
26 | test('componentDidMount', async () => {
27 | const app = enzyme.shallow(<App />);
> 28 | app.instance().componentDidMount()
| ^
29 | .then(() => {
I guess it makes sense since componentDidMount
is a void method, but I'm not sure why tutorials like this do it this way. Is it best to simply ignore that pattern?
This is another pattern that I found:
await app.instance().componentDidMount();
expect(axios_with_baseUrl.get).toHaveBeenCalled();
The bigger question is: are either of the above good patterns for mocking Axios in unit tests? Or should I just rely on something like axios-mock-adapter
?