How to dynamically test for typeof array within object?

304 Views Asked by At

I have an user object - I want to generate test for each user property and check if it's the right type. However as typeof array is an object assertion fails on array properties with "AssertionError: expected [ 1 ] to be an object".

I have therefore checked if the property is an array and then generate special test for it. I'm wondering if this is the right approach? I have a feeling I'm misssing something obvious.

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 is something like this:

let pureUser = {
    username: "JohnDoe123",
    id: 1,
    categories: [1,2,3,4]
}

User variable is defined elsewhere via got.js

1

There are 1 best solutions below

5
Junius L On

change your test to be pureUser[property].should.be.an.Array or user[property].should.be.an.Array

forEach

The forEach() method calls a provided function once for each element in an array, in order.

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]);
            //});
        }

    });

When you use forEach on pureUser, the parameter will be the objects properties, like username, id, etc

let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}

Object.keys(pureUser).forEach(property =>{
  console.log(property);
});

You can also access the array in your forEach function.

arr.forEach(item, index, arr)