[英]How to set a test for multiple fetches with Promise.all using jest
[英]Awaiting Promise.all in jest test
在Comp
組件中,我有一個Promise.all
在組件渲染時運行。 我試圖測試Promise.all
解決后, Promise.all
已調用OnItemsUpdate()
。
const Comp = ({OnItemsUpdate}) => {
Promise.all(items.map((item) => {
return datasource.UpdateItem(item);
})).then(() => {
return OnItemsUpdate();
});
// not including rest of the component for brevity's sake
}
it("Calls OnItemsUpdate when promises resolve", async () => {
const props = {
OnItemsUpdate: jest.fn();
}
expect(props.OnItemsUpdate).tohavebeencalledtimes(0);
const control = mount(<Comp {...props} />);
await datasource.UpdateItem
expect(props.OnItemsUpdate).tohavebeencalledtimes(1); // doesn't get called
})
等待OnItemsUpdate
無法正常工作expect(props.OnItemsUpdate).tohavebeencalledtimes(1)
仍返回0。
您可以使用setImmediate
類的setImmediate
來延遲斷言,直到PromiseJobs中的回調有機會運行后,才能解決此問題。
index.ts
:
import React from 'react';
export const Comp = ({ OnItemsUpdate, items, datasource }) => {
Promise.all(
items.map(item => {
return datasource.UpdateItem(item);
})
).then(() => {
return OnItemsUpdate();
});
// not including rest of the component for brevity's sake
return <div>test</div>;
};
單元測試:
import React from 'react';
import { Comp } from './';
import { mount } from 'enzyme';
describe('Comp', () => {
it('t1', done => {
const props = {
OnItemsUpdate: jest.fn(),
items: [1, 2],
datasource: {
UpdateItem: jest.fn().mockResolvedValue('whatever')
}
};
expect(props.OnItemsUpdate).toBeCalledTimes(0);
const wrapper = mount(<Comp {...props}></Comp>);
expect(props.datasource.UpdateItem).toBeCalledTimes(props.items.length);
expect(wrapper.html()).toMatchSnapshot();
setImmediate(() => {
expect(props.OnItemsUpdate).toBeCalledTimes(1);
done();
});
});
});
100%覆蓋率的測試結果:
PASS src/stackoverflow/57248527/index.spec.tsx
Comp
✓ t1 (63ms)
› 1 snapshot written.
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Snapshot Summary
› 1 snapshot written from 1 test suite.
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 1 written, 1 total
Time: 5.322s
快照:
// Jest Snapshot v1
exports[`Comp t1 1`] = `"<div>test</div>"`;
這是完整的演示: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57248527
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.