ReactJS - 測試



測試是確保任何應用程式中建立的功能是否符合業務邏輯和編碼規範的過程之一。React 建議使用 React 測試庫 來測試 React 元件,並使用 jest 測試執行器來執行測試。react-testing-library 允許隔離檢查元件。

可以使用以下命令在應用程式中安裝它:

npm install --save @testing-library/react @testing-library/jest-dom

建立 React 應用

建立 React 應用 預設配置了 React 測試庫jest 測試執行器。因此,測試使用 建立 React 應用 建立的 React 應用程式只需一個命令即可。

cd /go/to/react/application 
npm test

npm test 命令類似於 npm build 命令。兩者都會在開發者更改程式碼時重新編譯。一旦在命令提示符中執行該命令,它就會發出以下問題。

No tests found related to files changed since last commit.
Press `a` to run all tests, or run Jest with `--watchAll`.

Watch Usage
   › Press a to run all tests.
   › Press f to run only failed tests.
   › Press q to quit watch mode.
   › Press p to filter by a filename regex pattern.
   › Press t to filter by a test name regex pattern.
   › Press Enter to trigger a test run.  

按下 a 將嘗試執行所有測試指令碼,最後總結結果,如下所示:

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        4.312 s, estimated 12 s
Ran all test suites.

Watch Usage: Press w to show more. 

在自定義應用程式中進行測試

在本節中,讓我們使用 Rollup 捆綁器 編寫一個自定義 React 應用程式,並使用 React 測試庫jest 測試執行器對其進行測試。

首先,按照“建立 React 應用”章節中的說明,使用 Rollup 捆綁器建立一個新的 React 應用程式 react-test-app

接下來,安裝測試庫。

cd /go/to/react-test-app 
npm install --save @testing-library/react @testing-library/jest-dom

接下來,在您喜歡的編輯器中開啟應用程式。

接下來,在 src/components 資料夾下建立一個檔案 HelloWorld.test.js 來編寫 HelloWorld 元件的測試並開始編輯。

接下來,匯入 React 庫。

import React from 'react';

接下來,匯入測試庫。

import { render, screen } from '@testing-library/react'; import '@testing-library/jest-dom';

接下來,匯入我們的 HelloWorld 元件。

import HelloWorld from './HelloWorld';

接下來,編寫一個測試來檢查文件中是否存在 Hello World 文字

test('test scenario 1', () => {
   render(<HelloWorld />);
   const element = screen.getByText(/Hello World/i);
   expect(element).toBeInTheDocument();
});

完整的測試程式碼如下:

import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import HelloWorld from './HelloWorld';

test('test scenario 1', () => {
   render(<HelloWorld />);
   const element = screen.getByText(/Hello World/i);
   expect(element).toBeInTheDocument();
});

接下來,如果系統中尚未安裝 jest 測試執行器,請安裝它。

npm install jest -g

接下來,在應用程式的根資料夾中執行 jest 命令。

jest

接下來,在應用程式的根資料夾中執行 jest 命令。

PASS  src/components/HelloWorld.test.js
   √ test scenario 1 (29 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.148 s
Ran all test suites.
廣告