无法使用 Cypress.io 测试页脚的背景颜色,它会引发错误

soc*_*way 5 javascript cypress

无法使用 Cypress.io 测试背景颜色,在运行 cypress 测试时抛出以下错误;CypressError:重试超时:actual.equals 不是函数。通过安装chai-colorsnpm install chai-colors并在/support/index.js下添加以下内容

import chaiColors from 'chai-colors'
chai.use(chaiColors)
Run Code Online (Sandbox Code Playgroud)

cypress 测试如下:

describe("Background Color test", () => {
  //before(() => {
  //  cy.visit('https://sometesturl.com')
//  })
  it.only('Verify the backgroud color, this should work', () => {
     cy.visit('https://sometesturl.com')
      cy.get('#footer')
        .should('colored', '#f2e47d')
        .and('be.colored', '#f2e47d')
  })
})
Run Code Online (Sandbox Code Playgroud)

soc*_*way 19

我尝试过使用与颜色 #f2e47d 相对应的“eq”和“rgb”值。在以下链接中,来自 cypress.io 的“brian-mann”确认“match”始终适用于正则表达式。 https://github.com/cypress-io/cypress/issues/58 现在测试已成功断言页脚区域中的背景颜色值。

describe("Background Color test", () => {
  it.only('Verify the backgroud color, this should work', () => {
     cy.visit('https://sometesturl.com')
     cy.get('#footer')
       .should('have.css', 'background-color')
       .and('eq', 'rgb(242, 228, 125)')
  })
})
Run Code Online (Sandbox Code Playgroud)

  • 更简洁的语法是 `.should('have.css', 'background-color', 'rgb(242, 228, 125)')` (6认同)

Dav*_* Z. 6

chai-colors 只测试不同颜色表示的相等性。

要测试您的#footer元素是否具有特定的背景颜色,您需要使用Cypresscss()断言。

describe("Background Color test", () => {
  it.only('Verify the backgroud color, this should work', () => {
     cy.visit('https://sometesturl.com')
     cy.get('#footer')
       .should('have.css', 'background-color')
       .and('eq', 'rgb(242, 228, 125)')
  })
})
Run Code Online (Sandbox Code Playgroud)


Syl*_*are 5

看来您使用了错误的语法chai-colors。确保您已安装它:

npm install chai-colors --save-dev
Run Code Online (Sandbox Code Playgroud)

然后在您的测试中使用.should('have.css', 'background-color'),例如:

import chaiColors from 'chai-colors'
chai.use(chaiColors);

describe("Background Color test", () => {
  it.only('Verify the backgroud color, this should work', () => {
     cy.visit('https://sometesturl.com')
      cy.get('#footer')
        .should('have.css', 'background-color')
        .and('be.colored', '#f2e47d')
  });
});
Run Code Online (Sandbox Code Playgroud)

如果您收到类似#000000is not equal to#f2e47d之类的错误,则意味着您的选择器中get没有background-color,因此请确保您获得正确的元素。

资料来源:赛普拉斯食谱示例cypress-io#102

  • 由于您使用的是“chai-colors”,您还可以测试 CSS 颜色名称,例如“pink” (2认同)