【问题标题】:mock fetch request with fetch-mock using headers使用标头使用 fetch-mock 模拟 fetch 请求
【发布时间】: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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多