My page object file is like below
/// <reference types='cypress' />
const LOGIN_PAGE_HEADER_TEXT = '.welcome-message > h1';
class LoginPage {
get loginPageHeaderText() {
return cy.get(LOGIN_PAGE_HEADER_TEXT, {timeout: 140000});
}
}
export default LoginPage;
I want to use a custom command to check the Page header text and the text is dynamic
So I tried to write a custom command like below
Cypress.Commands.add('shouldContain', (element , text) => {
cy.get(element).should('contain.text', text)
})
but when I am using the custom command in my test file I am getting error. I am trying to use the custom command like below
cy.shouldContain(loginPage.loginPageHeaderText, 'Welcome')
The Error I am getting :
Timed out retrying after 60000ms: expected { Object (0, length) } to contain text 'Forgot Password?', but the text was ''
If I use this
Cypress.Commands.add('shouldContain', (element , text) => {
element.should('contain', 'text')
})
Then it shows the error
shouldcontain, text AssertionError object tested must be an array, a map, an object, a set, a string, or a weakset, but undefined given
Need Help
You have to just write text instead of 'text'. And instead of contain, use contain.text, this will do a partial match of the inner text of the element.
Cypress.Commands.add('shouldContain', (element , text) => {
element.should('contain.text', text)
})
Or, if you just want to use contain you can do this:
Cypress.Commands.add('shouldContain', (element , text) => {
element.invoke('text').should('contain', text)
})
Custom commands can't take other commands as parameters.
The way to do this is to build a Child Command
Cypress.Commands.add('shouldContain', {prevSubject:true}, (element , text) => {
cy.wrap(element).should('contain.text', text) // ✅ passes
})
You call it like this
loginPage.loginPageHeaderText.shouldContain('Welcome')
Passing loginPage.loginPageHeaderText as a parameter doesn't work because it is evaluated too soon.
The result is still undefined because the commands haven't started running yet.