[英]Testing method inside functional component in React using Jest / Enzyme
[英]Spy on a function inside functional component using React testing library
我正在嘗試使用反應測試庫監視 function 組件內的 function 。 我想測試是否在單擊按鈕時調用了handleClick
function。
這是我的代碼的摘錄
成分
const Foo = () => {
const handleClick = () => {}
return <div>
<button data-testid="button" onClick={handleClick}>Continue</button>
</div>
}
測試用例
it("should handle continue button click", async () => {
const { getByTestId } = render(<Foo />);
const button = getByTestId("button");
const spy = jest.spyOn(Foo, "handleClick");
act(() => {
fireEvent.click(button);
});
expect(spy).toHaveBeenCalled();
});
我得到的錯誤如下
Cannot spy the handleClick property because it is not a function; undefined given instead
有人可以幫忙嗎?
您不想監視handleClick
。 相反,您想測試handleClick
對組件的影響。 您的handleClick
回調是一個實現細節,並且作為一般規則,您不會對其進行測試。
您正試圖監視 handleClick,就好像它是 Foo 的一個屬性,即 function。
我可以將 handleClick 移動到另一個文件並將其導入到組件和測試中:
處理程序.js
export const handleClick = () => {}
成分
import { handleClick } from './handler.js'
const Foo = () => {
return <div>
<button data-testid="button" onClick={handleClick}>Continue</button>
</div>
}
測試用例
import * as handlers from './handler.js';
it("should handle continue button click", async () => {
const { getByTestId } = render(<Foo />);
const button = getByTestId("button");
const spy = jest.spyOn(handlers, "handleClick");
act(() => {
fireEvent.click(button);
});
expect(spy).toHaveBeenCalled();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.