Reputation: 81
I've came across this wall while i was mocking my project.
I make an axios.all request with 10 requests within it. How the hell do i mock it?
I'm currently using moxios to mock my axios http requests but it doesn't seem to have the functionality to deal with this problem.
Example:
axios.all([
axios.get(url1),
axios.get(url2),
axios.get(url3)
])
.then(axios.spread(function (r1, r2, r3) {
...
}))
.catch(err => {
console.error(err, err.stack);
});
Has anyone come accross this problem and have they found a solution?
Update:
I've just mocked each request invidually but it's a slow and painful process, is there a quicker more efficient way to do this?
Upvotes: 4
Views: 2626
Reputation: 3042
This is how I ended up mocking it.axios.all
in this case has 2 calls. mockAxios will loop twice. I used the axios-mock-adapter
package.
The Axios call (This applies to Promise.all
as well)
axios.all[
await axios.get('endpoint1'),
await axios.get('endpoint1'),
]
The mock
const mockData1 = [1, 2, 3];
const mockData2 = [3, 2, 1];
MockAxios.onAny().reply(config => {
// Use your config to return different responses.
// This mock will loop through every request in the Promise.all
if(config.url === 'endpoint1') {
return [200, {data: mockData1}, config];
} else if(config.url === 'endpoint2') {
return [200, {data: mockData2}, config];
}
});
Upvotes: 0
Reputation: 91
The way I got around this was using async
and await
to ensure that the function waits until it's finished running before making assertions.
I wasn't using moxios, but instead axios-mock-adapter but I have a feeling the issue can be resolved in the same way.
Given the above problem, I solved it like this...
In my component I have a method like so
getTheThing () {
axios
.all([
axios.get(`/api/endpoint/1`),
axios.get(`/api/endpoint/2`)
])
.then(
axios.spread((response1, response2) => {
this.setState({
firstThing: response1.data,
secondThing: response2.data
})
})
)
}
and in my tests...
mock = new MockAdapter(axios)
mock
.onGet(url1)
.reply(200, mockData1)
.onGet(url2)
.reply(200, mockData2)
it('should set issue state after fetching the requested issue', async () => {
await component.instance().getTheThing()
expect(whateverItIsYoureExpecting)
})
Upvotes: 1