【发布时间】:2017-11-06 13:30:41
【问题描述】:
我正在使用fetch-mock 来测试我的客户端操作创建者,以防对 BE 进行异步调用。
虽然所有获取请求都运行良好,但我很难做同样的事情来发布和提出请求。
这里附上一个代码示例,如果可行,我相信我的实际代码也可以。
我使用import fetchMock from 'fetch-mock' 来模拟响应和require('isomorphic-fetch') 直接替换默认提取
我添加了一些 cmets,但我确实得到了状态为 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 一起使用,但没有成功
- 如果有人知道我如何测试发送的 post 请求有效负载,我将不胜感激(在文档中看不到任何参考)
【问题讨论】:
标签: javascript unit-testing post mocking jestjs