简体   繁体   中英

How to use Template literals in Cypress on CSS selectors?

I am trying to make my tests more scalable/re-usable in Cypress by using Template Literals.

In Nightwatch I had done this by writing a function in the Page object model where I passed a parameter in the function and called the argument in the test as shown in the example.

I am new to to Cypress and I tried to read the documentation but could not really find something that resembles my problem. I tried it with variables, but that does not really solve my problem.

//Nightwatch Page Object model

selectMenuItem: function(name) {
       this.click(`.menuItem${name}`)

    return this; 
}
//Nightwatch Test
//Called in test by: 

.selectMenuItem('Payment')
.selectMenuItem('Contact')
//Cypress test

 it('Select menu item', function() {
        const name = 'Payment';

        .get(`.menuItem${name}`).click()

If I have multiple menu items, how can I interpolate the string on the same CSS selector?
The reason I ask is because Cypress team recommends not using the page object model pattern.

So how would one overcome this problem?

From a cursory search around the Cypress docs, it doesn't look like template literals would be supported inside of the .get() function, although I could be wrong. However, if you're just trying to iterate through all of the .menuItem selectors to find one with a specific name, you could just use

it('Select menu item', function() {
    const name = 'Payment';

    cy.get('.menuItem').contains(name).click();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM