javascript - 使用 fetch-mock 和 isomrphic-fetch 模拟 post 请求时,res.json() 未定义

标签 javascript unit-testing post mocking jestjs

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

这里附上一个代码示例,如果有效,我相信我的实际代码也会有效。

我正在使用import fetchMock from 'fetch-mock'用于 mock 响应和 require('isomorphic-fetch')直接替换默认的fetch

我添加了一些评论,但我确实得到了状态为 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 一起使用,但没有成功
  • 如果有人知道我如何测试发送的发布请求有效负载,我也将不胜感激(在文档中看不到任何相关引用)

最佳答案

在第一个 then 中,您没有使用关键字 return 显式返回

如果你不做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();
})

关于javascript - 使用 fetch-mock 和 isomrphic-fetch 模拟 post 请求时,res.json() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47138147/

相关文章:

javascript - SVG 动画,其中波峰/波浪路径通过 javascript 变成波谷/山谷

javascript - d3 的动态图表给出数组中重复元素的问题

JavaScript 文件无法与 servlet 一起正常工作

node.js - 如何对扩展抽象类读取环境变量的类进行单元测试

c# - 伪造 IDbSet<T> 并支持异步操作

java - Jersey POST 方法正在接收空值作为参数

javascript - 如何同时发布多个axios请求?

c++ - Google 可以模拟具有智能指针返回类型的方法吗?

html - POST 多个参数

javascript - ENTER 在 POST 上从\n 转换为\r\n