Reputation: 1091
I get the following error message when using: "TypeError: Cannot read property 'text' of undefined"
I´ve done exactly as they do in the documentation: https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Aliases
Can anyone see what i´m doing wrong?
beforeEach(() => {
cy.visit('http://localhost:4200/');
loginPage.login();
timeFilter.button.click();
cy.get('#title').invoke('text').as('text');
});
it('should show text', () => {
console.log(this.text);
});
Upvotes: 2
Views: 1612
Reputation: 1091
Read the cypress documentation and the problem i did was using arrow functions and i did not access the alias in a closure using a .then(). As soon as i did this, it worked:
cy.get('#title').invoke('text').as('text');
it('should show text', () => {
cy.get('#main').then(function () {
console.log(this.text);
});
});
OR use function()
instead of () =>
on the it()
callback
cy.get('#title').invoke('text').as('text');
it('should show text', function() {
console.log(this.text);
});
Upvotes: 4
Reputation: 4669
Text has always been a pain in cypress. This could be one of a few things:
1) Sometimes this.alias
doesn't work, try using:
cy.get('@text').then(text => console.log(text));
2) If the text is contained in an element below #title
, you will have to get that specific element. For example, #title
might be a div
, which contains an h1
element inside of it, so in that case you would need to use #title > h1
as your selector. Post your HTML and I'll be able to tell if that's the case
3) invoke('text')
almost never works, I'm not sure why. I find this works much more often cy.get('#title').then($el => el.text())
Upvotes: 1