I'm trying to mock an axios request in a function using moxios. Test is running fine and getting the expected result, but I don't think they way I implemented it is not a best practice at all. Could someone please suggest me a better way to achieve this instead of using setTimeout()
on tests?
....
componentDidMount() {
this.fetchSomething();
}
fetchSomething = () => {
Axios.get('https://someurl.com/api/1')
.then((response) => {
this.setState({ data: response.data.data });
})
.catch((error) => {
this.setState(error);
})
}
....
Test I've written:
beforeEach(() => {
moxios.install();
});
afterEach(() => {
moxios.uninstall();
})
it('should ', async (done) => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { data: 'hello' }
})
});
const wrapper = shallow(<TestComponent />);
setTimeout(() => {
expect(wrapper.instance().state.data).toEqual('hello')
done();
}, 500)
});
I think this is a better choice.
it('should ', (done) => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: { data: 'hello'}
}).then(() => {
expect(wrapper.instance().state.data).toEqual('hello');
done()
})
});
});
const wrapper = shallow(<TestComponent />);