我正在尝试测试一个调用API的组件,我遇到了MSW,我想这会很棒。
const server = setupServer(
rest.get('http://localhost:3001/vote/test-slug', (req, res, ctx) =>
res(ctx.delay(500), ctx.status(200), ctx.json({ data: {alreadyVoted: `1`}} )),
),
);这是我设置用来处理捕获的服务器。在幕后,我使用fetch在我的组件中进行API调用,它看起来像这样
apiFetchData = (params) => {
const res = await fetch(url, options);
const data = (await res.json()) || null;
const response: fetchJsonResponse = {
data,
statusCode: res.status,
error: res.status !== 200,
success: res.status === 200,
};
}我的组件有一个onload like效果,如下所示:
const component = () => {
useEffect(() => {
async function voteCheck() {
const result = await apiFetchData(
'http://localhost:3001/vote/test-slug',
);
if (result.data.alreadyVoted) {
setHasUserVoted(result.data.alreadyVoted);
}
setLoading(false);
}
voteCheck();
}, []);
}当我运行测试时
await act(async () => {
render(
<VoteButton />,
);
});我从我的apiFetchData中得到以下错误
UseEffect result {
data: {
error: 'invalid json response body at reason: Unexpected end of JSON input'
},
hasData: false,
statusCode: 500,
error: true,
errorType: 'application'
}(我使用jest-mock-fetch),我得到的结果是
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: <Buffer >, disturbed: false, error: null },
[Symbol(Response internals)]: {
url: undefined,
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: undefined
}
}我卡住了,看起来MSW正在捕获来自组件的请求,但我得到的响应似乎100%对fetch无效,我不知道哪里出了问题。任何帮助/建议都将不胜感激。
编辑:我的setupServer代码中的拼写错误
发布于 2021-11-08 11:13:07
好吧,所以,我终于想出了一个解决方案。
https://giters.com/mswjs/msw/issues/686发现了这个,它解释了我遇到的同样的问题。转到我们的I需要'polyfill‘获取。(TBH在这个阶段不确定这是什么意思)但是在评论中,人们链接到这个例子,特别是这个jest.setup:
现在我有了import 'whatwg-fetch';,它可以按预期工作。
https://stackoverflow.com/questions/69881929
复制相似问题