繁体   English   中英

如何动态测试对象中的typeof数组?

[英]How to dynamically test for typeof array within object?

我有一个用户对象 - 我想为每个用户属性生成测试并检查它是否是正确的类型。 但是,由于typeof数组是一个对象断言在数组属性上失败,并且“AssertionError:expected [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在别处定义

将您的测试更改为pureUser[property].should.be.an.Arrayuser[property].should.be.an.Array

的forEach

forEach()方法按顺序为数组中的每个元素调用一次提供的函数。

 let pureUser = { username: "JohnDoe123", id: 1, categories: [1,2,3,4] } 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])) { console.log('Yes, it\\'s an Array') //it(`should have property ${property}, type: array`, function () { // user.should.have.property(property); //}); } else { console.log('No, it\\'s not an Array') //it(`should have property ${property}, type: ${(typeof property)}`, function () { //user.should.have.property(property); // user[property].should.be.a(typeof pureUser[property]); //}); } }); 

在pureUser上使用forEach时,参数将是对象属性,如usernameid

 let pureUser = { username: "JohnDoe123", id: 1, categories: [1,2,3,4] } Object.keys(pureUser).forEach(property =>{ console.log(property); }); 

您还可以在forEach函数中访问该数组。

arr.forEach(item, index, arr)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM