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

时间:2017-04-06 14:09:39

标签: reactjs unit-testing fetch jestjs

我尝试使用fetch-mock和jest来模拟一个提取调用。我的提取调用是一个带请求正文和两个标题的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

任何帮助/提示都赞赏!

1 个答案:

答案 0 :(得分:4)

我通过不使用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);