如果有人能发现这段代码有什么问题,我将不胜感激。我自己没有看到问题,但它失败了。
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(...
. 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/