Could you please tell me how to test componentDidMount
function using enzyme
.I am fetching data from the server in componentDidMount
which work perfectly.Now I want to test this function.
here is my code https://codesandbox.io/s/oq7kwzrnj5
componentDidMount(){
axios
.get('https://*******/getlist')
.then(res => {
this.setState({
items : res.data.data
})
})
.catch(err => console.log(err))
}
I try like this
it("check ajax call", () => {
const componentDidMountSpy = jest.spyOn(List.prototype, 'componentDidMount');
const wrapper = shallow(<List />);
});
see updated code
https://codesandbox.io/s/oq7kwzrnj5
it("check ajax call", () => {
jest.mock('axios', () => {
const exampleArticles:any = {
data :{
data:['A','B','c']
}
}
return {
get: jest.fn(() => Promise.resolve(exampleArticles)),
};
});
expect(axios.get).toHaveBeenCalled();
});
You look like you're almost there. Just add the expect()
:
expect(componentDidMountSpy).toHaveBeenCalled();
If you need to check if it was called multiple times, you can use toHaveBeenCalledTimes(count)
.
Also, be sure to mockRestore()
the mock at the end to make it unmocked for other tests.
List.prototype.componentDidMount.restore();
To mock axios
(or any node_modules
package), create a folder named __mocks__
in the same directory as node_modules
, like:
--- project root
|-- node_modules
|-- __mocks__
Inside of there, make a file named <package_name>.js
(so axios.js
).
Inside of there, you'll create your mocked version.
If you just need to mock .get()
, it can be as simple as:
export default { get: jest.fn() }
Then in your code, near the top (after import
s), add:
import axios from 'axios';
jest.mock('axios');
In your test, add a call to axios.get.mockImplementation()
to specify what it'll return:
axios.get.mockImplementation(() => Promise.resolve({ data: { data: [1, 2, 3] } });
This will then make axios.get()
return whatever you gave it (in this case, a Promise
that resolves to that object).
You can then do whatever tests you need to do.
Finally, end the test with:
axios.get.mockReset();
to reset it to it's default mocked implementation.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.