简体   繁体   English

如何在 CSS 选择器上使用 Cypress 中的模板文字?

[英]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.我试图通过使用模板文字使我的测试在 Cypress 中更具可扩展性/可重用性。

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.在 Nightwatch 中,我通过在 Page 对象模型中编写一个函数来完成此操作,我在该函数中传递了一个参数,并在测试中调用了该参数,如示例所示。

I am new to to Cypress and I tried to read the documentation but could not really find something that resembles my problem.我是 Cypress 的新手,我尝试阅读文档,但无法真正找到与我的问题相似的内容。 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?如果我有多个菜单项,如何在同一个 CSS 选择器上插入字符串?
The reason I ask is because Cypress team recommends not using the page object model pattern.我问的原因是因为 Cypress 团队建议不要使用页面对象模型模式。

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.从 Cypress 文档周围的粗略搜索来看,看起来.get()函数内部不支持模板文字,尽管我可能是错的。 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但是,如果您只是想遍历所有.menuItem选择器以找到具有特定名称的选择器,则可以使用

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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