【问题标题】:Is there a way to set CSS properties like `display` using Cypress commands?有没有办法使用赛普拉斯命令设置 CSS 属性,如“显示”?
【发布时间】:2019-03-29 17:07:08
【问题描述】:

我想通过设置 display 属性来隐藏一个元素。

我尝试使用invoke 设置属性值,但它可能只适用于 HTML 属性?

cy.get('#hubspot-messages-iframe-container > iframe')
        .invoke('attr', 'display', 'none!important')
        .should('have.attr', 'display', 'none!important')

这似乎是在设置属性值,但该元素仍然可见,这让我相信它可能无法识别我的属性或者我使用了错误的命令。

按照建议尝试使用:

.css() 函数似乎没有按照应有的方式设置值:

这是我验证我自己的理智,选择器是正确的并且显示是none 哈哈:

【问题讨论】:

  • 你不能和!important一起使用,不过没关系,你不需要!important——这里没有作用。
  • 我只尝试了none,但没有成功,所以我也尝试了这种方式
  • 你能分享一下你用none尝试过的规范代码,但它没有用吗?我测试了我在本地分享的答案,所以它应该可以工作。
  • 不会是.css('display', 'none !important')而不是.css(display, none!important),指的是没有引号。
  • @MihailMinkov 猜对了,我尝试了这个"'display'", "'none'",它现在在输出中显示为.css('display', 'none'),但它仍然没有更新值

标签: javascript jquery html css cypress


【解决方案1】:

这似乎对人们有用。我相信initial !important 是某种参考,而不是实际值,也许这就是.css() 不起作用的原因。

Cypress.Commands.add('hideHubSpot', () => {
    cy.get('#hubspot-messages-iframe-container')
        .invoke('attr', 'style', 'display: none')
        .should('have.attr', 'style', 'display: none')

【讨论】:

  • 我确实在某些方面有所帮助,哈哈@James
  • 只是出于好奇,为什么是图片而不是代码sn-p?
【解决方案2】:

您可以使用invoke 调用css function from jQuery 来更改CSS。请注意,您的 !important 将不起作用,但您不需要它,因为通过 Javascript 设置 CSS 将覆盖项目上的任何其他样式。

如果需要,您可以使用Assertion List 中的have.css 断言进行检查。

这就是它的样子:

cy.get('#hubspot-messages-iframe-container > iframe')
  // use the .css function from jquery, since Cypress yields jquery elements
  .invoke('css', 'display', 'none')
  .should('have.css', 'display', 'none')

【讨论】:

  • 由于 .css() 的工作方式,这似乎不起作用 - 我相信这是样式表上的一条规则,它不允许 jquery 设置从 <body> 继承的值跨度>
【解决方案3】:

如果你追求的是 CSS,你可能应该使用样式而不是属性。

我不确定 cypress 是如何工作的,但我猜它是这样的:

cy.get('#hubspot-messages-iframe-container > iframe')
.invoke('style', 'display', 'none! important')
.should('have.style', 'display', 'none !important')

因为 display 不是属性,所以它是一个 CSS 属性,应该在样式属性中。

如果这不起作用,也许这样的事情可能:

cy.get('#hubspot-messages-iframe-container > iframe')
.invoke('attr', 'style', 'display: none! important')
.should('have.attr', 'style', 'display: none !important')

【讨论】:

  • 它对我不起作用。有效的是:cy.get('SELECTOR').invoke('attr', 'style', 'display: none !important').should('have.attr', 'style', 'display: none !important',)
  • 不行,cypress在should下没有have.style断言
  • 但我放的是have.attr而不是have.style
【解决方案4】:

P D 的回答对我有用。我也不必在我的任何样式中添加 !important,因此重申他所说的话,例如,此代码对我来说可以将调用的文本更改为粗体和绿色背景,前景色为白色:

cy.get($el).invoke('attr','style','font-weight: bold; color:#fff; background-color: #090;').invoke('text').then((text)=>{
   cy.wait(200);
});

我希望这对某人有所帮助。

布鲁斯

【讨论】:

猜你喜欢
  • 2018-05-01
  • 1970-01-01
  • 2022-08-02
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
相关资源
最近更新 更多