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

时间:2018-05-22 06:45:27

标签: reactjs tdd jestjs enzyme

我有一个名为Contact的react组件,后者又有一个名为Header的子组件。我将一个函数传递给名为 handleButtonClick()的Header组件。该组件中的函数调用如下:

<Header  handleButtonClick={this.openPopup} >

和openPopup()函数在Contact组件中定义,如下所示:

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 });

然后我如何编写测试用例。应该是这样的:

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

2 个答案:

答案 0 :(得分:3)

问题是浅层仅渲染一层深度,因此无法找到Header。只需使用console.log(comp.debug())即可查看呈现的内容。您可以使用dive更深入一级。

下一个问题是Header没有附加change个事件但是handleButtonClick。所以要触发这个,你需要像这样调用prop

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

答案 1 :(得分:0)

据我所知,您会看到此错误,因为您呈现的是<SparkTheme />组件的浅层。浅呈现不会呈现节点树中的所有子项,因此模拟不会找到标题组件。

浅呈现隐式鼓励您单独测试组件。因此,如果要使用浅渲染对其进行测试,则应直接渲染<Header />。如果没有看到标题组件的代码,很难给出更多建议。如何在您的问题中添加更多代码详细信息?