node.js - 未正确解析 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}
)似乎可以正常输入,但似乎没有被正确解析。我想要的是测试中的最终对象,它能够读取r
type的结果range
,并能够使用r.min
and读取其属性r.max
。
答案可能很明显,但我做错了什么?
解决方案
首先,“范围”在data
道具中,而不是直接在body
响应中。
其次,你JSON.stringify
在response.body
which 已经是一个字符串上做。
所以,使用
let r : range = JSON.parse(response.body).data;
奇怪的日志也是由于额外JSON.stringify
的response.body
. 你r
最终成为一个字符串,并且将for .. in
它作为一个字符数组进行迭代。
推荐阅读
- javascript - 在 foreach Firebase 函数中等待 - 每个循环在返回后执行
- javascript - 在 require 后监听 Socket.io 服务器
- r - 在 rms:::plot.anova.rms 中调整字体大小
- javascript - 在 javascript 中创建 csv 文件时,我无法让我的 åäö 显示在文件中
- flutter - 为什么 Gridview.count 没有用我的动态内容填充空间
- delphi - Tcxgriddbtableview - 对某一行中的几列求和
- tableau-api - 表格中的计算字段取决于列中的值
- emacs - 从组织模式表创建蜘蛛图
- javascript - 基于数量的 Woocommerce 变化价格产品总数
- json - 如何处理通过 JSON 传递的映射有意的 NULL 值?