.should('exist') 断言在赛普拉斯上是多余的吗?
Is the .should('exist') assertion redundant on Cypress?
让我们考虑一下我需要断言元素是否存在的情况。在柏树中有两种可能的方法:
1) cy.get('button').contains('Save')
2) cy.get('button').contains('Save').should('exist')
在这两种情况下,如果 'Save' 按钮不存在,测试将失败。
除了可能更好的代码 readability/maintainability 之外,我应该将 .should('exist') 添加到我的赛普拉斯测试中的原因是什么?
对于断言元素是否存在的用例,它们确实是多余的。
.contains()
产生一个 DOM 元素,根据 documentation,.should
产生与输入相同的元素。当 .should 产生不同的元素时有一些例外(如您在文档中所见)但在使用 should('exist')
的情况下,它们确实是多余的
如您所述,我个人也更喜欢添加 should
以提高可读性。实际上我更喜欢 .should('be.visible')
因为以下场景 - 当一个元素被隐藏或由于某些 CSS 问题被推出屏幕时,从用户角度来看它不存在。但是..
cy.get('button').contains('Save')
- 通过测试
cy.get('button').contains('Save').should('exist')
- 通过测试
cy.get('button').contains('Save').should('be.visible')
- 测试失败
实际上,直到 v4.0 发布(和 this PR is merged), you need to chain should('exist')
assertion if you chain any negative assertions yourself. This is because the default should('exist')
assertion is skipped when you chain your own assertions。
对于肯定的断言没有必要,因为它们不会传递 non-existent 个元素。
另见 Implicit should 'exist' assertion is not being applied on cy.get() when other assertion.
下面,元素.first-item
不存在但断言通过:
describe('test', () => {
it('test', () => {
cy.get('.first-item').should('not.have.class', 'is-selected');
});
});
让我们考虑一下我需要断言元素是否存在的情况。在柏树中有两种可能的方法:
1) cy.get('button').contains('Save')
2) cy.get('button').contains('Save').should('exist')
在这两种情况下,如果 'Save' 按钮不存在,测试将失败。
除了可能更好的代码 readability/maintainability 之外,我应该将 .should('exist') 添加到我的赛普拉斯测试中的原因是什么?
对于断言元素是否存在的用例,它们确实是多余的。
.contains()
产生一个 DOM 元素,根据 documentation,.should
产生与输入相同的元素。当 .should 产生不同的元素时有一些例外(如您在文档中所见)但在使用 should('exist')
的情况下,它们确实是多余的
如您所述,我个人也更喜欢添加 should
以提高可读性。实际上我更喜欢 .should('be.visible')
因为以下场景 - 当一个元素被隐藏或由于某些 CSS 问题被推出屏幕时,从用户角度来看它不存在。但是..
cy.get('button').contains('Save')
- 通过测试
cy.get('button').contains('Save').should('exist')
- 通过测试
cy.get('button').contains('Save').should('be.visible')
- 测试失败
实际上,直到 v4.0 发布(和 this PR is merged), you need to chain should('exist')
assertion if you chain any negative assertions yourself. This is because the default should('exist')
assertion is skipped when you chain your own assertions。
对于肯定的断言没有必要,因为它们不会传递 non-existent 个元素。
另见 Implicit should 'exist' assertion is not being applied on cy.get() when other assertion.
下面,元素.first-item
不存在但断言通过:
describe('test', () => {
it('test', () => {
cy.get('.first-item').should('not.have.class', 'is-selected');
});
});