【问题标题】:How to do testing on an array of objects using jest?如何使用玩笑对一组对象进行测试?
【发布时间】:2023-02-26 17:01:36
【问题描述】:
我有以下格式的对象数组 -
var a=[
{
"name":"Alex",
"DOB": 1677400634
},
{
"name":"John",
"DOB": 166400634
}
]
我想测试数组中每个对象的名称是一个字符串,DOB 是一个日期。我是开玩笑的初学者,在开玩笑时一直遇到困难。我该怎么做?
任何帮助将不胜感激。
【问题讨论】:
标签:
javascript
node.js
arrays
testing
jestjs
【解决方案1】:
我们可以使用describe来对多个测试进行分组,使用it来定义一个特定的测试。
您可以编写以下测试:
describe("array properties", () => {
it("should have string type for name and date type for DOB", () => {
var a = [
{
"name": "Alex",
"DOB": 1677400634
},
{
"name": "John",
"DOB": 166400634
}
];
// for each object in the array
a.forEach(obj => {
// test that 'name' property is a string
expect(typeof obj.name).toBe("string");
// test that 'DOB' property is a date
expect(new Date(obj.DOB).getTime()).toBeGreaterThan(0);
});
});
});
typeof 运算符返回值的类型。
getTime() 返回自纪元以来的毫秒数。
有关详细信息,请参阅本文:https://www.valentinog.com/blog/jest/