简体   繁体   English

在赛普拉斯中,如何测试一个属性等于多个值之一?

[英]In Cypress, how do you test that a property equals one of multiple values?

We are running some tests for a website in Cypress. 我们正在赛普拉斯的网站上进行一些测试。 In Chrome on Windows, the tests all pass. 在Windows上的Chrome中,所有测试均通过。 On a Mac, however, the widths of some elements are 2px wider than when on Windows. 但是,在Mac上,某些元素的宽度比Windows宽2px。 I understand that this shouldn't be the case, and we'll investigate that separately, but what I would like to know is how do you tests that a value of a test should fall within a range of values? 我了解情况并非如此,我们将对此进行单独调查,但是我想知道的是,您如何测试某个测试的值应在值的范围内?

This is the test that passes in Windows: 这是Windows中通过的测试:

it('checks Headline container, width & horizontal spacing', () => {
  cy.get('[data-cy=headline]')
    .should('have.css', 'width', '569px')
})

This one passes on a Mac. 这是在Mac上进行的。 The only change is the width being 571px instead of 569px . 唯一的变化是宽度为571px而不是569px

it('checks Headline container, width & horizontal spacing', () => {
  cy.get('[data-cy=headline]')
    .should('have.css', 'width', '571px')
})

Given that the actual should() test is against a string, how would you test that the width is either of two strings instead? 鉴于实际的should()测试是针对字符串的,那么如何测试宽度是否为两个字符串中的任意一个呢? Or an actual range of values? 还是实际值范围?

You could use closeTo for that. 您可以使用closeTo It would look like this: 它看起来像这样:

it('checks Headline container, width & horizontal spacing', () => {
  cy.get('[data-cy=headline]')
    .then($element => {
    expect($element.width())
      .closeTo(569, 2)
    })
})

The first number of closeTo is the wished number, the second number is the margin. closeTo的第一个数字是希望的数字,第二个数字是边距。 For example: If you have .closeTo(600, 150) the actual number should be between 450 and 750. So it isn't a very specific check. 例如:如果您具有.closeTo(600, 150)则实际数字应介于450和750之间。因此,这不是一个非常具体的检查。

I think I've found a better answer for my particular use case, though I really do like that there is a closeTo() method available. 我确实为我的特定用例找到了一个更好的答案,尽管我确实很喜欢有可用的closeTo()方法。

This is how I solved the problem: 这就是我解决问题的方法:

  it('checks Headline container, width & horizontal spacing', () => {
    cy.get('[data-cy=headline]')
      .should('have.css', 'width').and('match', /^(569|571)px/)
  })

I used a regular expression to match both the string 569px and 571px . 我使用了一个正则表达式来匹配字符串569px571px

This allows us to keep using should() for the tests while ensuring that the value matches one of the two specific sizes we were expecting. 这使我们可以继续使用should()进行测试,同时确保该值与我们期望的两个特定大小之一匹配。

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

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