我正在使用fetch-mock
在对 BE 进行异步调用的情况下测试我的客户端操作创建者。
虽然所有获取请求都运行良好,但我很难对发布和放置请求执行同样的操作。
这里附上一个代码示例,如果有效,我相信我的实际代码也会有效。
我正在使用import fetchMock from 'fetch-mock'
用于 mock 响应和 require('isomorphic-fetch')
直接替换默认的fetch
我添加了一些评论,但我确实得到了状态为 200 的响应(如果我将模拟响应状态更改为 400,我也会得到它。问题是 res.json() 导致未定义而不是模拟结果主体。 使用 JSON.stringify 是我在没有它就无法使其工作后使用的东西。
const responseBody = {response: 'data from the server'};
fetchMock.once('http://test.url', {
status: 200,
body: JSON.stringify(responseBody),
statusText: 'OK',
headers: {'Content-Type': 'application/json'},
sendAsJson: false
}, {method: 'POST'});
fetch('http://test.url',
{
method: 'post',
body: JSON.stringify({data: 'Sent payload'}),
headers : {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (res) {
expect(res.status).toEqual(200); // Pass
res.json();
})
.then(function (json) {
console.log(json); // print undefine
expect(json).toEqual(responseBody); // Fail expected value to equal: {"response": "data from the server"} Received: undefined
done();
})
- 模拟 GET 请求运行良好
- 我也尝试将它与 fetchMock.post 一起使用,但没有成功
- 如果有人知道我如何测试发送的发布请求有效负载,我也将不胜感激(在文档中看不到任何相关引用)
最佳答案
在第一个 then 中,您没有使用关键字 return
显式返回
如果你不做return,接下来的then就不知道这个值。这就是为什么你的 json 未定义。
例如:
var myInit = { method: 'GET', mode: 'cors', cache: 'default' };
fetch('https://randomuser.me/api/',myInit)
.then(function(res) {
return res.json()
})
.then(function(r) {
console.log(r)
})
所以,对你来说:
const responseBody = {response: 'data from the server'};
fetchMock.once('http://test.url', {
status: 200,
body: JSON.stringify(responseBody),
statusText: 'OK',
headers: {'Content-Type': 'application/json'},
sendAsJson: false
}, {method: 'POST'});
fetch('http://test.url',
{
method: 'post',
body: JSON.stringify({data: 'Sent payload'}),
headers : {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
})
.then(function (res) {
expect(res.status).toEqual(200); // Pass
return res.json(); // return here
})
.then(function (json) {
console.log(json); // print undefine
expect(json).toEqual(responseBody); // Fail expected value to equal: {"response": "data from the server"} Received: undefined
done();
})
关于javascript - 使用 fetch-mock 和 isomrphic-fetch 模拟 post 请求时,res.json() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47138147/