Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a dom element that contains the string or a url that I would like to visit. I have labelled the dom element with a data attribute for easy reference.

enter image description here

Above where it says 'Create Topic' in bold is the string and in the console, you can see it has a data-test='topicUrl attribute.

I want to capture this string value so that I can visit the url a a later point.

I followed the docs on Variables and Aliases and tried

cy.get('[data-test="topicUrl"]').invoke('text').as('Url')

so that I could visit the page by using

cy.visit(this.Url)

But that doesn't work, it errors out with TypeError: Cannot read property 'Url' of undefined in the console.

How do I grab the text in a DOM element so that I can use it to visit a url at a later point?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
695 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can cache it to a variable and issue the cy.visit in a callback to ensure the variable is populated:

let url;
cy.get('[data-test="topicUrl"]').invoke('text')
    .then( value => {
        url = value;
    });

cy.then(() => {

    return cy.visit(url);
});

Using cy.then() directly (instead of chaining it off of another command) isn't documented and might be removed in the future when cy.resolve( promise ) is implemented.

Maybe it's better to use cy.wrap().then(() => {}) which should work forever (?).

(going entirely from memory, so lemme know if it's not working and I'll update when I get a chance to run it.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...