I am writing an integration test for for a React application, i.e. a test that tests many components together, and I want to mock any calls to external services.
The issue is that the test seems to execute before the async callback is executed causing my tests to fail.
Is there anyway around this? Can I somehow wait for call async code to finish?
Here is some bad pseudo code to illustrate my point.
I would like to test that when I mount Parent, its Child component render the content that came back from an external service, which i will mock.
class Parent extends component {
render() {
<div>
<Child />
</div>;
}
}
class Child extends component {
DoStuff() {
aThingThatReturnsAPromise().then((result) => {
Store.Result = result;
});
}
render() {
DoStuff();
return <div>{Store.Result}</div>;
}
}
function aThingThatReturnsAPromise() {
return new Promise((resolve) => {
eternalService.doSomething(function callback(result) {
resolve(result);
});
});
}
When I do this in my test, it fails because the It gets executed before the callback gets fired.
jest.mock('eternalService', () => {
return jest.fn(() => {
return { doSomething: jest.fn((cb) => cb('fakeReturnValue');
});
});
describe('When rendering Parent', () => {
var parent;
beforeAll(() => {
parent = mount(<Parent />)
});
it('should display Child with response of the service', () => {
expect(parent.html()).toMatch('fakeReturnValue')
});
});
How do I test this? I understand angular resolves this with zonejs, is there an equivalent approach in React?