首页 > 解决方案 > 未正确解析 node.js 项目中带有 Jest 测试的 JSON 对象

问题描述

我有一个具有以下接口的对象:

export interface range {
  max: number,
  min: number
}

我从 GET 调用返回 - 下面列出了调用的函数。

export async function testHandler() {
  let result : range = {
    min: 101, 
    max: 202
  };
 
  return {
    body: JSON.stringify({
      data: result
    }),
    statusCode: 200
  };
}

这个想法是我想将范围对象的一个​​实例返回并解析到我的 Jest 测试中,如下所示:

import {  testHandler, range } from "..";

describe("TestEnv", () => {
  const expectedResponseShape = {
    body: expect.any(String),
    statusCode: expect.any(Number)
  };
 
describe("Test Range Test", () => {
it("should return the correct data shape: min and max, >= 0", async () => {
  const response = await testHandler();
  //make sure we're getting a response with an HTTP body
  expect(response).toEqual(expectedResponseShape);
  expect(response.statusCode).toEqual(200);

  let r : range = JSON.parse(JSON.stringify(response.body));
  expect(r).not.toBeUndefined();

  console.log(`range: ${r}`);
  console.log(`range.min: ${r.min}`);
  console.log(`range.max: ${r.max}`);


  for(var propName in r) {
    if(r.hasOwnProperty(propName)) {
        console.log(`propname ${propName} =:  ${r[propName]}`);   
    }
  }
});

});

所以这就是事情变得非常奇怪的地方。对于我的生活,我无法弄清楚为什么该r对象不会解析。日志的输出如下:

Test Range Test
      ✓ should return the correct data shape: min and max, >= 0 (46ms)

  console.log 
          range: {"data":{"min":101,"max":202}}

  console.log 
    range.min: undefined

  console.log 
    range.max: undefined

  console.log 
    propname 0 =:  {

  console.log 
    propname 1 =:  "

  console.log 
    propname 2 =:  d

  console.log 
    propname 3 =:  a

  console.log 
    propname 4 =:  t

  console.log 
    propname 5 =:  a

依此类推,直到

 console.log 
    propname 25 =:  2

  console.log 
    propname 26 =:  0

  console.log 
    propname 27 =:  2

  console.log 
    propname 28 =:  }

  console.log 
    propname 29 =:  }

所以对象的数据(即{min: 101, max:202})似乎可以正常输入,但似乎没有被正确解析。我想要的是测试中的最终对象,它能够读取rtype的结果range,并能够使用r.minand读取其属性r.max

答案可能很明显,但我做错了什么?

标签: node.jsjsonparsingjestjsstringify

解决方案


首先,“范围”在data道具中,而不是直接在body响应中。

其次,你JSON.stringifyresponse.bodywhich 已经是一个字符串上做。

所以,使用

let r : range = JSON.parse(response.body).data; 

奇怪的日志也是由于额外JSON.stringifyresponse.body. 你r最终成为一个字符串,并且将for .. in它作为一个字符数组进行迭代。


推荐阅读