使用 React Testing Library 和 Mirage 模擬元件的網路請求
使用 Mirage 直接在您使用 React Testing Library 編寫的測試中,模擬個別 API 端點。
本指南適用於已在其 React 應用程式中使用 React Testing Library 的人員。
步驟 1:安裝 Mirage
首先,請確保您已將 Mirage 新增至您的專案
# Using npm
npm install --save-dev miragejs
# Using Yarn
yarn add --dev miragejs
步驟 2:在測試中建立伺服器
在測試檔案中,從 Mirage 匯入 Server
,建立一個伺服器,並模擬您的程式碼需要的 API 端點
// src/__tests__/App.test.js
import React from "react"
import { render, waitForElement } from "@testing-library/react"
import App from "../App"
import { createServer } from "miragejs"
let server
beforeEach(() => {
server = createServer()
// If your API is at a different port or host than your app, you'll need something like:
// server = createServer({
// environment: "test",
// urlPrefix: "http://api.acme.com:3000",
// })
})
afterEach(() => {
server.shutdown()
})
it("shows the users from our server", async () => {
server.get("/users", () => [
{ id: 1, name: "Luke" },
{ id: 2, name: "Leia" },
])
const { getByTestId } = render(<App />)
await waitForElement(() => getByTestId("user-1"))
await waitForElement(() => getByTestId("user-2"))
expect(getByTestId("user-1")).toHaveTextContent("Luke")
expect(getByTestId("user-2")).toHaveTextContent("Leia")
})
當 <App />
元件被渲染,且 React 向 /users
發出網路請求時,Mirage 將會攔截並使用上面的資料回覆。
請注意,我們在每個測試之後都呼叫了 server.shutdown()
,以便 Mirage 有機會自行清理,而不會洩漏到其他測試中。
若要深入了解測試,請閱讀應用程式測試指南。