• #">配置#
  • #">示例#
  • #">了解更多#

    因为 Vitest 运行在 Node 环境中,所以模拟网络请求是一件非常棘手的事情;由于没有办法使用 Web API,因此我们需要一些可以为我们模拟网络行为的包。推荐使用 Mock Service Worker 来进行这个操作。它可以模拟 REST 和 GraphQL 网络请求,并且与框架无关。
    Mock Service Worker (MSW) 通过拦截测试发出的请求进行工作,允许你在不更改任何应用程序代码的情况下使用它。在浏览器中,它使用 Service Worker API。在 Node 中,对于 Vitest,它使用 node-request-interceptor。了解有关 MSW 的更多信息,可以去阅读他们的 introduction。

    配置#

    如下,你可以在你的 配置文件 中使用。

    1. import { afterAll, afterEach, beforeAll } from 'vitest'
    2. import { setupServer } from 'msw/node'
    3. import { graphql, rest } from 'msw'
    4. const posts = [
    5. {
    6. userId: 1,
    7. id: 1,
    8. title: 'first post title',
    9. body: 'first post body',
    10. },
    11. // ...
    12. ]
    13. export const restHandlers = [
    14. rest.get('https://rest-endpoint.example/path/to/posts', (req, res, ctx) => {
    15. return res(ctx.status(200), ctx.json(posts))
    16. }),
    17. ]
    18. const graphqlHandlers = [
    19. graphql.query('https://graphql-endpoint.example/api/v1/posts', (req, res, ctx) => {
    20. return res(ctx.data(posts))
    21. }),
    22. ]
    23. const server = setupServer(...restHandlers, ...graphqlHandlers)
    24. // 在所有测试之前启动服务器
    25. beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
    26. // 所有测试后关闭服务器
    27. afterAll(() => server.close())
    28. // 每次测试后重置处理程序 `对测试隔离很重要`
    29. afterEach(() => server.resetHandlers())

    使用 onUnhandleRequest: ‘error’ 配置服务器可以确保每当有没有相应请求处理程序的请求时都会引发错误。

    示例#

    我们有一个使用 MSW 的完整工作示例:React Testing with MSW。

    了解更多#

    MSW 能做的还有很多。你可以访问 cookie 和查询参数、定义模拟错误响应等等!要查看您可以使用 MSW 做什么,请阅读 their documentation.

    Vitest