【问题标题】:res.json() is undefined when mocking post request with fetch-mock and isomrphic-fetch使用 fetch-mock 和 isorphic-fetch 模拟发布请求时 res.json() 未定义
【发布时间】:2017-11-06 13:30:41
【问题描述】:

我正在使用fetch-mock 来测试我的客户端操作创建者,以防对 BE 进行异步调用。 虽然所有获取请求都运行良好,但我很难做同样的事情来发布和提出请求。

这里附上一个代码示例,如果可行,我相信我的实际代码也可以。

我使用import fetchMock from 'fetch-mock' 来模拟响应和require('isomorphic-fetch') 直接替换默认提取

我添加了一些 cmets,但我确实得到了状态为 200 的响应(如果我将模拟响应状态更改为 400,我也会得到它。问题是 res.json() 导致未定义而不是模拟结果正文. 使用 JSON.stringify 是我在没有它无法使其工作之后使用的东西。

const responseBody = {response: 'data from the server'};

fetchMock.once('http://test.url', {
  status: 200,
  body: JSON.stringify(responseBody),
  statusText: 'OK',
  headers: {'Content-Type': 'application/json'},
  sendAsJson: false
}, {method: 'POST'});

fetch('http://test.url',
{
  method: 'post',
  body: JSON.stringify({data: 'Sent payload'}),
  headers : {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
})
.then(function (res) {
  expect(res.status).toEqual(200); // Pass
  res.json();
})
.then(function (json) {
  console.log(json); // print undefine
  expect(json).toEqual(responseBody); // Fail expected value to equal: {"response": "data from the server"} Received: undefined

  done();
})
  • 模拟 GET 请求运行良好
  • 我也尝试将它与 fetchMock.post 一起使用,但没有成功
  • 如果有人知道我如何测试发送的 post 请求有效负载,我将不胜感激(在文档中看不到任何参考)

【问题讨论】:

    标签: javascript unit-testing post mocking jestjs


    【解决方案1】:

    在你的第一个然后,你没有明确的回报,关键字return

    如果你不返回,那么下一个 then 不知道值。这就是您的 json 未定义的原因。

    例如:

    var myInit = { method: 'GET', mode: 'cors', cache: 'default' };
    
    fetch('https://randomuser.me/api/',myInit)
      .then(function(res) {
         return res.json()
      })
      .then(function(r) {
         console.log(r)
      })
    

    所以,对你来说:

    const responseBody = {response: 'data from the server'};
    
    fetchMock.once('http://test.url', {
      status: 200,
      body: JSON.stringify(responseBody),
      statusText: 'OK',
      headers: {'Content-Type': 'application/json'},
      sendAsJson: false
    }, {method: 'POST'});
    
    fetch('http://test.url',
    {
      method: 'post',
      body: JSON.stringify({data: 'Sent payload'}),
      headers : {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    })
    .then(function (res) {
      expect(res.status).toEqual(200); // Pass
      return res.json(); // return here
    })
    .then(function (json) {
      console.log(json); // print undefine
      expect(json).toEqual(responseBody); // Fail expected value to equal: {"response": "data from the server"} Received: undefined
    
      done();
    })
    

    【讨论】:

    • 工作,我的错,谢谢!!!此外,如上所述,“如果有人知道我如何测试发送的 post 请求有效负载,我将不胜感激(在文档中看不到任何参考)”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 2017-01-26
    相关资源
    最近更新 更多