Javascript 模拟服务工作者/节点isn';我不能工作,我可以';我不明白为什么
如果有人能发现这段代码的任何错误,我将非常感激。我自己没有看到问题,但它失败了Javascript 模拟服务工作者/节点isn';我不能工作,我可以';我不明白为什么,javascript,reactjs,typescript,api,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 =
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文件中,我有:
从'jest fetch mock'导入{enablefetchmock};
...
enableFetchMocks();
因此,fetch()
根本没有被调用
我对发布的代码进行了3次更改以使其正常工作:
导入并调用disableFetchMocks()
在获取之前添加等待(…
)
将URL更改为http://localhost/test
,以解决一个测试错误,该错误表示我需要使用绝对URL
以下是工作代码(由PyCharm整理为AirB&B风格):
从“msw/node”导入{setupServer};
从“msw”导入{rest};
从“jest fetch mock”导入{disableFetchMocks};
描述(‘模拟API’,()=>{
const testCall=jest.fn();
const server=setupServer(
...[
休息,起床http://localhost/test',(请求、分辨率、ctx)=>{
log('此行正在运行');
testCall();
返回res(ctx.json({message:'success'}));
}),
],
);
test('test',async()=>{
disableFetchMocks();
server.listen();
待命http://localhost/test“,{method:'GET'});
expect(testCall).tohaveBeenCall();
server.close();
});
});
当您运行在节点环境中运行的测试时,此fetch函数不存在(它的意思是:global.fetch),因此您需要进行多边形填充
我建议安装npm包“whatwg fetch”
npm install whatwg-fetch
然后像这样使用它:
import 'whatwg-fetch';
这可能会有帮助2。虽然这回答了OP的问题,但在真正经过测试的代码中,我没有wait
beforefetch
,也不太可能添加它。在这种情况下,我们应该怎么做?3.同样,我真正经过测试的代码不使用绝对URL,这是典型的。我如何使用相对URL?为此我可以吻你回答!我是第二个@l2silver,老兄,你太棒了!非常感谢!我的头撞到了墙上。。。