I'm new to jest/enzyme and am trying to mock a call to an aync function that returns a Promise, the call is made inside a react component in the componentDidMount method.
The test is attempting to test that componentDidMount sets the array returned by the Promise in the state.
The issue I'm having is that the test finishes and passes before the array is added to the state. I am trying to use the 'done' callback to have the test wait until the promise resolves but this doesn't seem to work.
I have tried to move the expect calls to the line before the done() call but that doesn't seem to work either.
Can anyone tell me what I am doing wrong here?
Component being tested:
componentDidMount() {
this.props.adminApi.getItems().then((items) => {
this.setState({ items});
}).catch((error) => {
this.handleError(error);
});
}
My test:
import React from 'react';
import { mount } from 'enzyme';
import Create from '../../../src/views/Promotion/Create';
import AdminApiClient from '../../../src/api/';
jest.mock('../../../src/api/AdminApiClient');
describe('view', () => {
describe('componentDidMount', () => {
test('should load items into state', (done) => {
const expectedItems = [{ id: 1 }, { id: 2 }];
AdminApiClient.getItems.mockImplementation(() => {
return new Promise((resolve) => {
resolve(expectedItems);
done();
});
});
const wrapper = mount(
<Create adminApi={AdminApiClient} />
);
expect(wrapper.state().items).toBe(expectedItems);
});
});
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…