首頁  >  文章  >  web前端  >  使用 Vite 和 TS 在 React 專案中設定 Vitest、MSW 和 Playwright - 第 3 部分

使用 Vite 和 TS 在 React 專案中設定 Vitest、MSW 和 Playwright - 第 3 部分

Linda Hamilton
Linda Hamilton原創
2024-10-11 10:37:30450瀏覽

Playwright 是一款適用於 Web 應用的與框架無關的端對端測試(也稱為 E2E 或整合測試)工具。 Playwright 擁有豐富的開發經驗,讓寫作變得簡單,並且能夠輕鬆應對更改測試。


1.安裝劇作家

要設定 Playwright,請執行以下指令:

npm init playwright@latest

系統將引導您完成終端中的設定精靈。當提示 「在哪裡放置端對端測試?」 時,您可以將其設定為 src/tests(如早期教學中的建議)。

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 3

將腳本新增至 package.json

在 package.json 中,加入以下兩個腳本來執行 Playwright 測試:

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 3

這允許您在開發和 CI 環境中執行測試。

編劇配置

playwright.config.ts 檔案應配置如下:

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 3

配置的主要變化:

  • use.baseURL:這設定了開發伺服器的基本 URL,因此您不必在每個測試中都編寫它。
  • webServer:此區塊說明如何啟動開發伺服器。除非您處於 CI 環境中,否則它將重複使用已運行的伺服器。
  • testDir:Playwright 應該在其中尋找 E2E 測試的目錄(在本例中為 src/tests/e2e)。

2. 配置 MSW 進行瀏覽器測試

到目前為止,MSW 已設定為在 Node.js 環境中模擬 API 回應。不過,由於 Playwright 使用真實瀏覽器進行測試,因此需要配置 MSW 在瀏覽器環境下運作。

建立一個新的 JavaScript 模組,用於註冊 MSW 服務工作線程以進行基於瀏覽器的測試:

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 3

3. 在開發模式下註冊Worker

要在應用程式以開發模式運行時啟動 MSW Worker,請將以下內容新增至應用程式的根模組(例如 src/main.tsx):

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 3

確保在 .env 檔案中設定 VITE_API_MOCK 環境變數:

VITE_API_MOCK="true"

4. 編寫 E2E 測試

現在您可以為應用程式中的流程編寫 E2E 測試。這是劇作家測驗的例子:

Configure Vitest, MSW and Playwright in a React project with Vite and TS - Part 3

5. 運行測試

要執行 E2E 測試,請使用下列指令:

npm run test:e2e:ci

這將以 CI 模式執行測試,這對於自動化管道很有用。

以上是使用 Vite 和 TS 在 React 專案中設定 Vitest、MSW 和 Playwright - 第 3 部分的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn