因为 Vitest 运行在 Node 环境中,所以模拟网络请求是一件非常棘手的事情;由于没有办法使用 Web API,因此我们需要一些可以为我们模拟网络行为的包。推荐使用 Mock Service Worker 来进行这个操作。它可以模拟 REST 和 GraphQL 网络请求,并且与框架无关。
Mock Service Worker (MSW) 通过拦截测试发出的请求进行工作,允许你在不更改任何应用程序代码的情况下使用它。在浏览器中,它使用 Service Worker API。在 Node 中,对于 Vitest,它使用 node-request-interceptor。了解有关 MSW 的更多信息,可以去阅读他们的 introduction。
配置#
如下,你可以在你的 配置文件 中使用。
import { afterAll, afterEach, beforeAll } from 'vitest'import { setupServer } from 'msw/node'import { graphql, rest } from 'msw'const posts = [{userId: 1,id: 1,title: 'first post title',body: 'first post body',},// ...]export const restHandlers = [rest.get('https://rest-endpoint.example/path/to/posts', (req, res, ctx) => {return res(ctx.status(200), ctx.json(posts))}),]const graphqlHandlers = [graphql.query('https://graphql-endpoint.example/api/v1/posts', (req, res, ctx) => {return res(ctx.data(posts))}),]const server = setupServer(...restHandlers, ...graphqlHandlers)// 在所有测试之前启动服务器beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))// 所有测试后关闭服务器afterAll(() => server.close())// 每次测试后重置处理程序 `对测试隔离很重要`afterEach(() => server.resetHandlers())
使用 onUnhandleRequest: ‘error’ 配置服务器可以确保每当有没有相应请求处理程序的请求时都会引发错误。
示例#
我们有一个使用 MSW 的完整工作示例:React Testing with MSW。
了解更多#
MSW 能做的还有很多。你可以访问 cookie 和查询参数、定义模拟错误响应等等!要查看您可以使用 MSW 做什么,请阅读 their documentation.
