您好,登錄后才能下訂單哦!
要使用Jest測(cè)試React Hooks中的useState
,你需要遵循以下步驟:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom @testing-library/user-event
Counter.js
的文件,其中包含一個(gè)簡(jiǎn)單的計(jì)數(shù)器組件,該組件使用useState
來(lái)管理計(jì)數(shù)器的狀態(tài):import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Increment</button>
<p>Count: {count}</p>
</div>
);
};
export default Counter;
Counter.test.js
的文件,用于編寫(xiě)測(cè)試用例:import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Counter from './Counter';
describe('Counter', () => {
it('renders the increment button and count text', () => {
render(<Counter />);
const buttonElement = screen.getByText(/Increment/i);
const countTextElement = screen.getByText(/Count: 0/i);
expect(buttonElement).toBeInTheDocument();
expect(countTextElement).toBeInTheDocument();
});
it('increments the count when the button is clicked', () => {
render(<Counter />);
const buttonElement = screen.getByText(/Increment/i);
fireEvent.click(buttonElement);
const countTextElement = screen.getByText(/Count: 1/i);
expect(countTextElement).toBeInTheDocument();
});
});
package.json
文件中添加一個(gè)test
腳本,以便可以運(yùn)行測(cè)試:"scripts": {
"test": "jest"
}
npm test
命令以執(zhí)行測(cè)試用例。如果一切正常,你應(yīng)該會(huì)看到類(lèi)似以下的輸出:PASS ./Counter.test.js
Counter
? renders the increment button and count text (23 ms)
? increments the count when the button is clicked (7 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.5 s
這表明你已成功地使用Jest測(cè)試了React Hooks中的useState
。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。