将模拟 Service Worker (msw) 与 @web/test-runner 一起使用

发布于 2025-01-10 09:21:24 字数 1175 浏览 1 评论 0原文

我正在尝试使用 @web/test-runner (和剧作家)设置 msw。问题是我不知道测试运行程序如何拾取mockServiceWorker.js(它使用浏览器,而不是像jest这样的nodejs)。有一个关于业力的例子: https://github.com/mswjs/examples/tree/master/ example/with-karma,可能我必须做类似的事情,但我不知道从哪里开始。欢迎任何提示。

我不确定这是否重要,但让我分享一下我的 web.test-runner.config.js

import vite from 'vite-web-test-runner-plugin'
import { playwrightLauncher } from '@web/test-runner-playwright';

export default {
  plugins: [ vite() ],
  coverageConfig: {
    include: [ 'src/**/*.{svelte,js,jsx,ts,tsx}' ]
  },
  browsers: [
    playwrightLauncher({ product: 'chromium' })
  ],
  testRunnerHtml: testFramework => `
  <!DOCTYPE html>
    <html>
      <head>
        <script type="module">
          window.global = window;
          window.process = { env: {} };
        </script>
        <script type="module" src="${testFramework}"></script>
      </head>
    </html>
};

和我的测试命令

"test": "web-test-runner \"test/**/*.test.ts\"",

I am trying to setup msw with @web/test-runner (and playwright). The problem is that I don't know how the mockServiceWorker.js can be picked up by the test runner (which uses browser, not nodejs like jest). There is an example with karma:
https://github.com/mswjs/examples/tree/master/examples/with-karma, probably I have to do something similar but I have no idea where to start. Any hints are welcome.

I am not sure if it is important, but let me share my web.test-runner.config.js

import vite from 'vite-web-test-runner-plugin'
import { playwrightLauncher } from '@web/test-runner-playwright';

export default {
  plugins: [ vite() ],
  coverageConfig: {
    include: [ 'src/**/*.{svelte,js,jsx,ts,tsx}' ]
  },
  browsers: [
    playwrightLauncher({ product: 'chromium' })
  ],
  testRunnerHtml: testFramework => `
  <!DOCTYPE html>
    <html>
      <head>
        <script type="module">
          window.global = window;
          window.process = { env: {} };
        </script>
        <script type="module" src="${testFramework}"></script>
      </head>
    </html>
};

and my test command

"test": "web-test-runner \"test/**/*.test.ts\"",

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

路弥 2025-01-17 09:21:24

简短的答案是通过导入映射到模块并重新导出 IIFE 分布式模块来代替 msw 导入。

这里描述的设置很长,请阅读 如何将 MSW 查询模拟与 @web/test-runner 和 StoryBook 集成,还有一个指向工作源的链接。

The short answer is to substitute of msw import by import maps to module with re-export of IIFE distributed module.

The setup is quite long to be described here, read more in How to integrate MSW queries mocking with @web/test-runner and StoryBook, there is also a link to working sources.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文