[英]How to test functions in React with Jest and Enzyme
我有一個名為Contact的react組件,它反過來有一個名為Header的子組件。我將一個函數傳遞給我的Header組件,名為handleButtonClick() 。 該組件中的函數調用如下:
<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
問題是淺層僅渲染一層深度,因此無法找到Header
。 只需使用console.log(comp.debug())
來查看呈現的內容。 您可以使用dive
更深一層。
接下來的問題是Header
沒有附加change
事件但handleButtonClick
。 所以要觸發這個,你需要像這樣調用prop
:
comp.find(Header).prop("handleButtonClick")({target: {value: 'someValue'}})
據我所知,你會看到這個錯誤,因為你是淺呈現<SparkTheme />
組件。 淺呈現不會呈現節點樹中的所有子項,因此模擬不會找到標題組件。
淺呈現隱式鼓勵您單獨測試組件。 因此,如果要使用淺渲染對其進行測試,則應直接渲染<Header />
。 如果沒有看到標題組件的代碼,很難給出更多建議。 如何在您的問題中添加更多代碼細節?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.