您好,登錄后才能下訂單哦!
要使用Jest測試React Hooks的自定義Hooks,你需要遵循以下步驟:
npm install --save-dev jest @testing-library/react-hooks react-test-renderer
setupTests.js
的文件,并添加以下內容:import { renderHook, act } from '@testing-library/react-hooks';
import { render, fireEvent, waitFor } from '@testing-library/react';
global.renderHook = renderHook;
global.act = act;
global.render = render;
global.fireEvent = fireEvent;
global.waitFor = waitFor;
這將使得@testing-library/react-hooks
和@testing-library/react
中的函數在全局范圍內可用。
useCounter.js
的文件,其中包含一個簡單的自定義Hook:import { useState } from 'react';
const useCounter = (initialValue = 0) => {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return { count, increment, decrement };
};
export default useCounter;
useCounter.test.js
的文件,用于編寫針對useCounter
Hook的測試:import { renderHook, act } from '@testing-library/react-hooks';
import useCounter from './useCounter';
describe('useCounter', () => {
it('should increment the counter', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it('should decrement the counter', () => {
const { result } = renderHook(() => useCounter(5));
act(() => {
result.current.decrement();
});
expect(result.current.count).toBe(4);
});
});
package.json
中添加一個名為test
的腳本,如下所示:"scripts": {
"test": "jest"
}
npm test
來執行測試。這就是使用Jest測試React Hooks的自定義Hooks的方法。請注意,這里的示例僅用于演示目的,實際項目中可能需要更復雜的測試用例。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。