Would love to have a workaround for this timeout
See original GitHub issueIn Angular testing for a service that implements $http, we’re using to doing this:
$httpBackend.flush();
What this does is it takes any outstanding requests and processes them so that you can then begin the assertion process. See its docs for more.
Anyway, I’m bringing this up as an example because it would be really nice to be able to have this for the axios mocker. Instead of this flush() method or something similar, we’re forced to create a timeout with a zero millisecond duration and then nest all of our expectations within that timeout. For an example of this, see here:
import { expect } from 'chai';
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { fetchPost } from './lib'
describe('Lib', () => {
it('Should return data from response', (done) => {
let mockAdapter = new MockAdapter(axios);
mockAdapter.onGet('http://awesome.com/posts').reply(200, {
data: {
posts: ['Intro to git']
}
});
let response = fetchPost();
setTimeout(() => {
expect(response.posts[0]).to.be.equal('Intro to git');
done();
}, 0)
});
});
I’ve confirmed in my own local code that without the timeout, you indeed cannot expect response.posts[0] to be resolved, but you can inside the timeout. I don’t like this syntax though because it forces all of the code to be nested another level, it’s not as linear, and it assumes some things about how your axios promiser is implemented (e.g. it breaks on an otherwise perfectly functioning custom wrapper that I wrote for fun).
Would it be possible to have some sort of $httpBackend.flush(); equivalent for this axios mocker?
Thanks!
Issue Analytics
- State:
- Created 7 years ago
- Reactions:4
- Comments:6 (1 by maintainers)

Top Related StackOverflow Question
If I understand correctly, you’re saying that the code above should be reformatted to the following:
Correct?
Assuming this is the case, that would work in situations where the function that generates the HTTP request returns a promise, but the function might not do that. Imagine if this were how fetchPost were defined:
In other words, instead of using promises to pass the data around, we’re using a simple pub/sub model. In this situation we’re required to use a timeout. Would love for that to not have to be the case.
The best way I found to modify the async action creator to return the http.get promise and then make the test an async function and set the action dispatcher with an await call. You can then make assertions after the action dispatch.