乐闻世界logo
搜索文章和话题

Cypress 如何测试某个元素是否不存在?

7 个月前提问
3 个月前修改
浏览次数70

5个答案

1
2
3
4
5

在Cypress中,要检验某个元素是否不存在,可以使用.should('not.exist')断言。这个断言会成功地通过,如果在DOM中找不到期望的元素。以下是一个简单的例子,展示了如何在Cypress中验证一个元素不存在:

javascript
// 假设我们想要确保一个具有特定ID的元素不存在于页面中 cy.get('#element-to-find').should('not.exist');

这行代码会指示Cypress去查找具有ID element-to-find 的元素,并验证它确实不存在于DOM中。

在实际的测试场景中,你可能遇到需要等待某个异步操作完成后再检查元素是否存在的情况。例如,如果有一个元素是在某个动作执行后被从DOM中移除的,你可能想要使用cy.wait()来等待这个操作完成:

javascript
// 假设执行某个动作后,元素会被从DOM中移除 cy.click('#remove-element-button'); // 触发移除元素的动作 cy.wait(1000); // 等待1000毫秒 cy.get('#element-to-remove').should('not.exist'); // 然后检查元素是否被移除

在这个例子中,我们首先触发了一个按钮点击事件,它会导致页面上的一个元素被移除。然后我们告诉Cypress等待一秒钟,以确保那个动作有足够的时间去完成移除元素的操作,最后我们检查元素是否真的不存在了。

总的来说,使用.should('not.exist')是一个确保元素不存在于页面中的简单而有效的方法。记住,在某些情况下,可能需要等待特定的异步事件完成后才能正确进行此类检查。

2024年6月29日 12:07 回复

Well this seems to work, so it tells me I have some more to learn about .should()

shell
cy.get('.check-box-sub-text').should('not.exist');
2024年6月29日 12:07 回复

You can also search for a text which is not supposed to exist:

shell
cy.contains('test_invite_member@gmail.com').should('not.exist')

Here you have the result in Cypress: 0 matched elements

enter image description here

Reference: Docs - Assertions, Existence

2024年6月29日 12:07 回复

Use .should('not.exist') to assert that an element does not exist in the DOM.


Do not use not.visible assertion. It would falsely pass in < 6.0, but properly fail now:

shell
// for element that was removed from the DOM // assertions below pass in < 6.0, but properly fail in 6.0+ .should('not.be.visible') .should('not.contain', 'Text')

Migration Docs here: Migrating-to-Cypress-6-0

2024年6月29日 12:07 回复

cy.get('[data-e2e="create-entity-field-relation-contact-name"]').should('not.exist');

might lead to some false results, as some error messages get hidden. It might be better to use

shell
.should('not.visible');

in that case.

2024年6月29日 12:07 回复

你的答案