如何使用 Jest 和 Enzyme 在 React 中测试函数

How to test functions in React with Jest and Enzyme

我有一个名为 Contact 的 React 组件,它又有一个名为 Header.I 的子组件,我将一个函数传递到我的 Header 组件中,名为 handleButtonClick()。该函数在组件中这样调用:

<Header  handleButtonClick={this.openPopup} >

contact组件中定义了openPopup()函数,如下所示:

openPopup = () => this.setState({ popupOpen: true });

所以,我正在尝试使用 jest 和 Enzyme 测试此功能:

it("calls the `openPopup` function", () => {
        const onMockFunction = jest.fn();
        const comp = shallow(
            <SparkTheme>
                <Contact handleButtonClick={onMockFunction} />
            </SparkTheme>
        );
        comp.find(Header).simulate("change");
        expect(onMockFunction).toBeCalledTimes(1);
});

所以,当我 运行 这个测试时,我收到一条错误消息:

Method “simulate” is only meant to be run on a single node. 0 found instead.

这是什么问题?有人可以帮我解决这个问题吗?

注意:此外,如果我有另一个函数需要一些参数,如下所示,

setValue = e => this.setState({ value: e.target.value });

那我该如何编写测试 case.Should 应该是这样的:

comp.find(Header).simulate("change", event);

我无法检查它是否失败。请指导我。

编辑 1: 执行 comp.debug() 后,我得到的输出是:

<div>
        <Header contactCount={3} handleButtonClick={[Function: bound ]} buttonText="View all">
          Site Contact From HTML
        </Header>
        <ContactList name="displayContacts" data={{...}} />
        <Popup open={false} onRequestClose={[Function: bound ]}>
          <styled.h3>
            Contacts
          </styled.h3>
          <SearchBar onRequestClear={[Function: bound ]} setValue={[Function: bound ]} value="" />
          <styled.div>
            <ContactList hasLeftPadding={true} popupDisplay={true} data={{...}} />
          </styled.div>
        </Popup>
      </div>

我现在收到的错误消息是:

comp
            .dive()
            .find(Header)
            .prop("handleButtonClick")({ target: { value: "someValue" } });

是:

TypeError: ShallowWrapper::dive() can not be called on Host Components

据我所知,您看到此错误是因为您浅渲染了 <SparkTheme /> 组件。浅渲染不会渲染节点树中的所有 children,因此模拟不会找到 Header 组件。

浅渲染隐含地鼓励您单独测试组件。因此,如果你想使用浅层渲染来测试它,你应该直接渲染 <Header /> 。如果没有看到您的 header 组件的代码,很难给您更多的建议。如何为您的问题添加更多代码细节?

问题是 shallow 只渲染了一层 deep,所以它找不到 Header。只需使用 console.log(comp.debug()) 即可查看呈现的内容。您可以使用 dive 更深入一层。

下一个问题是 Header 没有附加 change 事件但是 handleButtonClick。因此,要触发此操作,您需要像这样调用 prop

comp.find(Header).prop("handleButtonClick")({target: {value: 'someValue'}})