[英]How to pass function to a custom hook while writing unit test in jest React.js
我面臨的問題是,我必須編寫index.js 中使用的自定義鈎子的單元測試,請參閱此實現,其中我將函數作為參數傳遞。 所以我不知道如何在單元測試中將函數傳遞給鈎子。 我是新手。 我需要緊急幫助來實現單元測試的 100% 覆蓋率。
useBrowserFwdBackButton.ts (自定義鈎子可用的文件)
import React from 'react';
const useBrowserFwdBackButton = (fn: any) => {
const cb = React.useRef(fn); // init with fn, so that type checkers won't assume that current might be undefined
React.useEffect(() => {
cb.current = fn;
}, [fn]);
React.useEffect(() => {
const onForwardBackButtonEvent = (...args: any[]) => cb.current?.(...args);
window.addEventListener('popstate', onForwardBackButtonEvent);
return () => window.removeEventListener('popstate', onForwardBackButtonEvent);
}, []);
};
export default useBrowserFwdBackButton;
index.js (鈎子從功能組件調用的地方)
useBrowserFwdBackButton((e) => {
e.preventDefault();
if (attachmentListLength !== 0) {
dispatch(deleteGoogleDocument(attachmentList));
}
});
假設您使用 jest 和@testing-library/react-hooks
進行鈎子測試
您可以使用jest.fn()
創建模擬功能,例如。
const mockFunction = jest.fn();
const { result } = renderHook(() => useBrowserFwdBackButton(mockFunction));
const { .... } = result.current;
// since it's attached to windows event, you need to trigger the "popstate" event
// expects here
expect(mockFunction).toBeCalledTimes(1);
附加信息(觸發窗口事件) 如何在使用 vue-test-utils 進行單元測試期間觸發窗口事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.