【问题标题】:Mock Service Worker / Node isn't working and I can't see why模拟服务工作者/节点不工作,我不明白为什么
【发布时间】:2020-12-10 02:43:58
【问题描述】:

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

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();
  })
})

【问题讨论】:

    标签: javascript reactjs typescript api


    【解决方案1】:

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

    import { enableFetchMocks } from 'jest-fetch-mock';
    ...
    enableFetchMocks();
    

    所以,fetch() 根本没有被调用。

    我对发布的代码进行了 3 处更改以使其正常工作:

    1. 导入并调用disableFetchMocks()
    2. fetch(...之前添加await
    3. 将 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();
      });
    });
    

    【讨论】:

    • 2.尽管这回答了 OP 问题的文本,但在实际测试的代码中,我在 fetch 之前没有 await 并且不太可能添加它。在这种情况下我们应该怎么做? 3. 同样,我实际测试的代码不使用绝对 URL,这是典型的。如何使用相对 URL?
    【解决方案2】:

    当您在节点环境中运行测试时,在此 fetch 函数中不存在(这意味着:global.fetch),因此您需要制作一个 polyfill。

    我建议安装 npm 包 'whatwg-fetch'

    npm install whatwg-fetch
    

    并像这样使用它:

    import 'whatwg-fetch';
    

    这个video 可以提供帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多