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:
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:
Share Improve this question edited Nov 9, 2023 at 0:34 TesterDick 10.6k1 gold badge16 silver badges34 bronze badges asked Nov 21, 2022 at 10:16 yasith ranganayasith rangana 2994 silver badges14 bronze badges3 Answers
Reset to default 10Please 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)
If you want to check the result of searching the users array, do it outside the .find()
function.
If no user with the required role is found, the .find()
function returns undefined
(never null or empty string or empty array).
Ref Array.prototype.find()
cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
/*
e.g users = [
{ userRole: 'admin', username: '...', password: '...' },
{ userRole: 'userRole', username: '...', password: '...' },
]
*/
const user = users.find(user => user.userRole === 'userRole')
if (!user) {
throw new Error('user is undefined')
}
signIn(user.username, user.password);
})
Empty, null, and undefined values are falsy so you can throw an error if not truthy.
cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
const user = users.find(user => {
if(!user) {
throw new Error('user is empty, null, or undefined', user)
}
return user.userRole === 'userRole';
});
signIn(user.username, user.password);
});