使用标头使用fetch-mock模拟获取请求

Ria*_*Ria 4 unit-testing fetch reactjs jestjs

我尝试使用fetch-mock和开玩笑模拟提取呼叫。我的提取调用是带有请求正文和两个标头的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)});
Run Code Online (Sandbox Code Playgroud)

我在测试中尝试了以下方法:

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);
Run Code Online (Sandbox Code Playgroud)

但这给了我这个错误:

Unmatched POST to http://someUrl
Run Code Online (Sandbox Code Playgroud)

任何帮助/提示表示赞赏!

Ria*_*Ria 5

我通过不使用解决了此问题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);
Run Code Online (Sandbox Code Playgroud)