javascript - 模拟服务 worker /节点不工作,我不明白为什么

标签 javascript reactjs typescript api

如果有人能发现这段代码有什么问题,我将不胜感激。我自己没有看到问题,但它失败了。

import React from "react"
import {setupServer} from "msw/node"
import {rest} from "msw"

describe("mocking apis", () => {
  const testCall = jest.fn()
  const server = setupServer(
    ...[
      rest.get("/test", (req, res, ctx) => {
        console.log('This line is never run')
        testCall()
        return res(ctx.json({message: "success"}))
      }),
    ]
  )

  test("test", async () => {
    server.listen()
    fetch("/test", {method: "GET"})
    expect(testCall).toHaveBeenCalled()
    server.close();
  })
})

最佳答案

我也有这个问题。过了一会儿,我明白了原因。在我的 src/setupTests.js我有的文件:

import { enableFetchMocks } from 'jest-fetch-mock';
...
enableFetchMocks();
所以,fetch()根本没有被调用。
我对发布的代码进行了 3 处更改以使其正常工作:
  • 导入并调用disableFetchMocks() .
  • 添加 await之前 fetch(... .
  • 将 URL 更改为 http://localhost/test ,以解决说我需要使用绝对 URL 的测试错误。

  • 这是工作代码(由 PyCharm 清理为 AirB&B 风格):
    import { setupServer } from 'msw/node';
    import { rest } from 'msw';
    import { disableFetchMocks } from 'jest-fetch-mock';
    
    describe('mocking apis', () => {
      const testCall = jest.fn();
      const server = setupServer(
        ...[
          rest.get('http://localhost/test', (req, res, ctx) => {
            console.log('This line is run');
            testCall();
            return res(ctx.json({ message: 'success' }));
          }),
        ],
      );
    
      test('test', async () => {
        disableFetchMocks();
        server.listen();
        await fetch('http://localhost/test', { method: 'GET' });
        expect(testCall).toHaveBeenCalled();
        server.close();
      });
    });
    

    关于javascript - 模拟服务 worker /节点不工作,我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63510555/

    相关文章:

    Javascript - 数组连接到另一个

    javascript - 动态 SVG 元素未正确使用 mask

    javascript - Google 跟踪代码管理器 - 存储单击的 div/按钮的 ID

    javascript - 如何修复index.tsx中的解析错误: Unexpected token,预期 ","?

    typescript - 将 Object<T> 转换为 Object<A>,其中 A 包含在 T 中

    javascript - 我真的可以用 javascript 调整图像大小吗?

    reactjs - npm install 覆盖现有的 package-lock.json 并中断 Modal

    javascript - Next.js Jest 28 - 无法转换 SVG 文件

    reactjs - 在 useEffect() 内部使用 useDispatch() 时,操作似乎不会立即调用

    javascript - 如何在 typescript 的输入搜索框中添加去抖动时间?