【发布时间】:2017-04-06 14:09:39
【问题描述】:
我尝试使用 fetch-mock 和玩笑来模拟 fetch 调用。我的 fetch 调用是一个带有请求正文和两个标头的 POST 请求。
我的代码如下所示:
let payload = JSON.stringify({"some" : "value"});
let headers = new Headers({"Accept": "application/json", "Content-Type": "application/json"});
let options = {method: "POST", body: payload, headers: headers};
fetch('http://someUrl', options)
.then(response => response.json())
.then(data => {this.data = data})
.catch(e => {console.log("exception", e)});
我在测试中尝试了以下方法:
let fetchMock = require('fetch-mock');
let response = {
status: 200,
body: {data : "1234"}
};
let payload = JSON.stringify({"some" : "value"});
let headers = new Headers({"Accept": "application/json", "Content-Type": "application/json"});
let options = {"method": "POST", "body": payload, "headers": headers};
fetchMock.mock('http://someUrl', response, options);
但它给了我这个错误:
Unmatched POST to http://someUrl
感谢任何帮助/提示!
【问题讨论】:
-
你找到答案了吗
-
并非如此。我更改了代码,因此不再使用
new Headers。这样更容易。 -
你能给我那个代码吗
-
我发布了一个答案,希望对您有所帮助
标签: reactjs unit-testing fetch jestjs