【发布时间】:2019-04-22 23:50:03
【问题描述】:
我有一个用户对象 - 我想为每个用户属性生成测试并检查它是否是正确的类型。但是,由于 typeof 数组是一个对象,因此数组属性上的断言失败,并显示“AssertionError:预期 [1] 是一个对象”。
因此,我检查了该属性是否是一个数组,然后为它生成特殊测试。我想知道这是否是正确的方法?我有一种感觉,我错过了一些明显的东西。
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
it(`should have property ${property}, type: array`, function () {
user.should.have.property(property);
});
} else {
it(`should have property ${property}, type: ${(typeof pureUser[property])}`, function () {
user.should.have.property(property);
user[property].should.be.a(typeof pureUser[property]);
});
}
});
pureUser 是这样的:
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
用户变量通过 got.js 在别处定义
【问题讨论】:
-
似乎没有定义用户变量。
-
是的,我在代码的其他位置获取了用户变量。这段代码确实会生成测试并检查类型,但正如我所说,我认为我做错了。
-
是否可以在您的问题中发布用户变量中的数据?
-
user 变量与 pureUser 完全相同,所以 user = { username: "JohnDoe123", id: 1, categories: [1,2,3,4] }。不同之处在于 pureUser 是硬编码的,用户是从 API 中获取的,并针对预期结果( pureUser )进行测试。
标签: javascript node.js mocha.js chai should.js