自訂池
警告
這是進階 API。如果你只是在執行測試,你可能不需要這個。它主要由函式庫作者使用。
Vitest 在池中執行測試。預設有幾個池
threads
使用node:worker_threads
執行測試(隔離透過新的工作執行緒內容提供)forks
使用node:child_process
執行測試(隔離透過新的child_process.fork
程序提供)vmThreads
使用node:worker_threads
執行測試(但隔離透過vm
模組而非新的工作執行緒內容提供)browser
使用瀏覽器提供者執行測試typescript
對測試執行類型檢查
你可以透過指定檔案路徑提供你自己的池
export default ({
: {
// will run every file with a custom pool by default
: './my-custom-pool.ts',
// you can provide options using `poolOptions` object
: {
: {
: true,
},
},
// you can also specify pool for a subset of files
: [
['**/*.custom.test.ts', './my-custom-pool.ts'],
],
},
})
API
在 pool
選項中指定的檔案應匯出一個函式(可以是非同步),它接受 Vitest
介面作為其第一個選項。此函式需要傳回一個與 ProcessPool
介面相符的物件
import { ProcessPool, WorkspaceProject } from 'vitest/node'
export interface ProcessPool {
name: string
runTests: (files: [project: WorkspaceProject, testFile: string][], invalidates?: string[]) => Promise<void>
close?: () => Promise<void>
}
此函式只會呼叫一次(除非伺服器設定已更新),而且通常建議在該函式內初始化測試所需的所有內容,並在呼叫 runTests
時重複使用它。
當排定執行新的測試時,Vitest 會呼叫 runTest
。如果 files
為空,它不會呼叫它。第一個引數是一個元組陣列:第一個元素是對工作空間專案的參考,第二個元素是測試檔案的絕對路徑。在呼叫 runTests
之前,會使用 sequencer
對檔案進行排序。有可能(但不太可能)兩次出現同一個檔案,但它永遠會有不同的專案 - 這是透過 vitest.workspace.ts
設定實作的。
Vitest 會等到 runTests
執行完畢才會結束執行(也就是說,它只會在 runTests
解決後才會發出 onFinished
)。
如果您使用自訂池,您必須自己提供測試檔案及其結果 - 您可以參照 vitest.state
(最重要的部分是 collectFiles
和 updateTasks
)。Vitest 使用 @vitest/runner
套件中的 startTests
函式來執行此操作。
若要讓不同處理程序之間進行通訊,您可以使用 vitest/node
中的 createMethodsRPC
建立方法物件,並使用您偏好的任何通訊形式。例如,若要使用 birpc
與 WebSockets 通訊,您可以撰寫類似這樣的程式碼
import { createBirpc } from 'birpc'
import { parse, stringify } from 'flatted'
import { WorkspaceProject, createMethodsRPC } from 'vitest/node'
function createRpc(project: WorkspaceProject, wss: WebSocketServer) {
return createBirpc(
createMethodsRPC(project),
{
post: msg => wss.send(msg),
on: fn => wss.on('message', fn),
serialize: stringify,
deserialize: parse,
},
)
}
若要確保收集到每個測試,您會呼叫 ctx.state.collectFiles
並將其報告給 Vitest 報告器
async function runTests(project: WorkspaceProject, tests: string[]) {
// ... running tests, put into "files" and "tasks"
const methods = createMethodsRPC(project)
await methods.onCollected(files)
// most reporters rely on results being updated in "onTaskUpdate"
await methods.onTaskUpdate(tasks)
}
您可以在 pool/custom-pool.ts 中看到一個簡單的範例。