等待Promise.all在开玩笑的测试

时间:2019-07-29 06:53:28

标签: javascript reactjs enzyme jest

Comp组件中,我有一个Promise.all组件在渲染时运行。我试图测试Promise.all解决后,是否已调用OnItemsUpdate()。

const Comp = ({OnItemsUpdate}) => {
    Promise.all(items.map((item) => {
        datasource.UpdateItem(item);
    })).then(() => {
        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 props.OnItemsUpdate

    expect(props.OnItemsUpdate).tohavebeencalledtimes(1); // doesn't get called

})

等待OnItemsUpdate无效,因为expect(props.OnItemsUpdate).tohavebeencalledtimes(1)仍返回0。

1 个答案:

答案 0 :(得分:0)

您可以通过使用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