带有正则表达式的赛普拉斯“have.attr”

Dan*_*iel 12 cypress

在 Cypress 中,我可以通过像这样的精确文本来匹配属性的值:

cy.get("my-element")
  .should("have.attr", "title", "Exact title")
Run Code Online (Sandbox Code Playgroud)

但是,有没有办法通过子字符串或正则表达式来匹配属性的值?就像是:

cy.get("my-element")
  .should("have.attr", "title", /Partial title/)
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我拥有的最好的:

cy.get("my-element")
  .should("have.attr", "title")
  .then(title => expect(title).to.match(/Partial title/));
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 23

根据赛普拉斯文档have.attr来自chai-jquery

attr(name[, value])

使用 断言选择的第一个元素具有给定的属性.attr()。可选地,也声明一个特定的值。返回值可用于链接。

$('#header').should.have.attr('foo');
expect($('body')).to.have.attr('foo', 'bar');
expect($('body')).to.have.attr('foo').match(/bar/);
Run Code Online (Sandbox Code Playgroud)

它只直接为属性取一个确切的值。但是,由于返回值会更改主题,因此您可以使用Cypress 文档中所示的链接

cy
  .get('nav')                          // yields <nav>
  .should('be.visible')                // yields <nav>
  .should('have.css', 'font-family')   // yields 'sans-serif'
  .and('match', /serif/)
Run Code Online (Sandbox Code Playgroud)

在你的情况下,这将是

cy.get("my-element")
  .should("have.attr", "title")
  .and("match", /Partial title/);
Run Code Online (Sandbox Code Playgroud)

  • 除了 `.and("match", /Partial title/);`,也可以使用 `.and("contain", 'Partial title');`。这样你就不需要正则表达式了。 (7认同)