在 Enzyme 和 Jest 中等待条件(最终一致性,超时断言)

Wait for condition in Enzyme and Jest (eventual consistency, assert with timeout)

我有一个简单的测试:

import React from 'react';
import GenericButton from 'components/buttons/GenericButton';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';

describe('Generic Button', () => {
    test('Button action called when clicked', () => {
        var clicked = false;
        const component = shallow(
            <GenericButton action={() => {
                clicked = true;
            }}
            id="testComponent"/>
        );

        component.find('testComponent').first().simulate('click');
        expect(clicked).toBeTruthy();
    });
});

然而,随着操作最终完成,这将失败,

如果我将断言设置为最终发生(例如使用 setTimeout)它将起作用

但是,如果我在断言之前执行以下操作会更好(在使用 jasmine 的示例中找到)

        waitsFor(() => {
            return clicked;
        }, "the value to change", 1000);

enzyme/jest 的等效调用是什么?


编辑:组件内容

render() {
    return <Button id={this.props.id}
                   key={this.props.id}
                   onClick={() => this.props.action()}
                   bsStyle={this.props.style}>
               {this.props.text}
           </Button>;
}

(按钮是第 3 方库组件)

要测试是否正确添加了点击处理程序,请将间谍程序传递到您的评论中,模拟点击并检查是否调用了间谍程序。这样做不需要使用 waitsFor.

import React from 'react';
import GenericButton from 'components/buttons/GenericButton';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';

describe('Generic Button', () = > {
  test('Button action called when clicked', () = > {
    const action = jest.fn();
    const component = shallow(
      <GenericButton action={action}
            id="testComponent"/>
    );
    component.find('Button').first().simulate('click');
    expect(action).toHaveBeenCalled();
  });
});