0
我是新来的jest /酶,我试图模拟对返回Promise的异步函数的调用,调用是在componentDidMount方法中的反应组件内进行的。Jest模拟异步调用内部反应组件
测试正在尝试测试componentDidMount设置状态中Promise返回的数组。
我遇到的问题是测试在数组添加到状态之前完成并通过。我正在尝试使用'done'回调让测试等待,直到承诺解决,但这似乎不起作用。
我已经尝试在done()调用之前将预期调用移动到该行,但似乎也不起作用。
任何人都可以告诉我我在做什么错吗?
组件进行测试:
componentDidMount() {
this.props.adminApi.getItems().then((items) => {
this.setState({ items});
}).catch((error) => {
this.handleError(error);
});
}
我的测试:
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);
});
});
});
感谢您的解释,这种方法很好地工作!也可以通过使用Promise.reject()和try/catch块并在p.catch()上等待来测试错误情况。 – lachy