javascriptcypresschai

Check if a variable is empty/null/undefined


This code block is used to read an excel file and get user data by a given user role.

But if the user role does not exist in the excel file, it will return an undefined value.

How to de we check that the user variable is not undefined or null?

 cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
            const user = users.find(user => {
                return user.userRole === 'userRole';
            });
    
            cy.wrap(user).should('not.be.empty');
            cy.wrap(user).should('not.be.a',undefined)
            cy.wrap(user).should('not.be.a',null)
            signIn(user.username, user.password);
        });

cy.wrap(user).should('not.be.empty') (this part working but not others)

This is the error I received:

enter image description here


Solution

  • Please see chaijs .a(type[, msg])

    Asserts that the target’s type is equal to the given string type. Types are case insensitive.

    expect(undefined).to.be.an('undefined')
    

    The .a() or .an() is doing a typeof check that returns a string, so you just need to quote the "undefined" type

    cy.wrap(user).should('not.be.a', "undefined")
    

    or drop the .a to do a reference check instead

    cy.wrap(user).should('not.be', undefined)