我尝试使用fetch-mock和jest模拟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感谢任何帮助/提示!
发布于 2017-12-14 14:53:17
我通过不使用new Headers解决了这个问题。
let payload = JSON.stringify({"some" : "value"});
let 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 headers = {"Accept": "application/json", "Content-Type":
"application/json"};
let options = {method: "POST", headers: headers, body: payload};
fetchMock.mock('http://someUrl', response, options);https://stackoverflow.com/questions/43257671
复制相似问题