javascript Cypress:设置属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47131842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:13:38  来源:igfitidea点击:

Cypress: set attribute value

javascriptcypress

提问by R.Ro

I have just started exploring Cypress and came across such a problem: is it possible to select a concrete attribute and change its value like in Selenium with the help of JavascriptExecutor? For example lets take this simple piece of code

我刚刚开始探索 Cypress 并遇到了这样一个问题:是否有可能在 Selenium 的帮助下选择一个具体的属性并更改其值JavascriptExecutor?例如,让我们使用这段简单的代码

input id="mapsearch" type="textbox" class="form-control" name="address" test=""

Is it possible to get the test attribute and assign my own value?

是否可以获取测试属性并分配我自己的值?

回答by Jennifer Shehane

Yes. Anything you can do in JavaScript is possible within Cypress tests. For the html above, you could do this within Cypress using .invoke():

是的。在 Cypress 测试中,您可以在 JavaScript 中做的任何事情都是可能的。对于上面的 html,您可以使用以下方法在 Cypress 中执行此操作.invoke()

cy.get('input[test]')
  .invoke('attr', 'test', 'my new value')
  .should('have.attr', 'test', 'my new value')

Cypress uses jQuery under the hood, so you can invoke any function in jQuery like this. You could alternatively use plain JavaScript after yielding the input using .then():

Cypress 在底层使用 jQuery,因此您可以像这样调用 jQuery 中的任何函数。您也可以在使用.then()以下方法生成输入后使用纯 JavaScript :

cy.get('input[test]').then(function($input){
    $input[0].setAttribute('test', 'my new value')
  })
  .should('have.attr', 'test', 'my new value')