2017-04-06 52 views
2

我尝试使用fetch-mock和jest来模拟取回调用。我的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 

任何帮助/提示不胜感激!

+0

您是否发现了ans –

+0

并非如此。我改变了我的代码,所以我不再使用'新的Headers'。这使它更容易。 – Ria

+0

你可以给我那个代码 –

回答

2

我解决了这个问题,不使用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);