Cypress,如何检查输入到字段中的文本?

7
我可以通过以下方式验证结果页面上的文本是否出现在“某个地方”:

it.only('can verify an input element has certain text typed into it', function() {
  cy.visit('http://google.com')
  cy.get("input[name=q]").type('abc123{enter}')  // with or without the {enter}
  cy.contains('abc123') // Anywhere on the page :(
})

但是我该如何验证我在中输入的文本呢?

我尝试使用链式方法定位到元素:

it.only('can verify an input element has certain text typed into it', function() {
  cy.visit('http://google.com')
  cy.get("input[name=q]").type('abc123{enter}')
  cy.get("input[name=q]").contains('abc123')
})

但我却获得

CypressError: Timed out retrying: Expected to find content: 'abc123' within the element: <input.gLFyf.gsfi> but never did.

我尝试了cy.get("input[name=q]").contains('abc123')cy.contains('input[name=q]', 'abc123'),但两者都超时失败了。

1
你弄清楚这里发生了什么了吗 https://stackoverflow.com/q/60348107?我很好奇。 - Snow
请见下方回答。 - Michael Durrant
我指的是你之前提到的问题,关于Vim中的^$锚点,但该问题已被删除。 - Snow
3个回答

18

.contains更改为使用.should('have.value'...

cy.get("input[name=q]").type('abc123{enter}')
cy.get("input[name=q]").should('have.value', 'abc123')

2
也许我们可以将该测试写成一行代码,并断言 cy.get("input[name=q]").type('abc123{enter}').should('have.value', 'abc123') - soccerway
2
@soccerway 取决于情况,因为他在末尾键入了“{enter}”,他可能正在发布可以触发页面重新加载的表单。如果发生了这种情况,不确定Cypress是否有时间进行断言。但是除此之外,就像Cypress在这里所示的那样:https://example.cypress.io/commands/actions - Jordan Kowal

0

不要使用 contains,可以使用 "then()" 读取已经在输入框中输入的文本。如下:

cy.get("input[name=q]").type('abc123').then(function($input){ const value = $input.text() expect(value.includes('abc123')).to.be.true })


0

也许你不喜欢这个想法,但这只是一个建议,这样你就不必每次都调用cy.get

你可以为你的输入名称设置一个常量值(可以在外部文件中),例如:

export const inputField = () => cy.get('input[name=q]');

每当您调用inputField时,它将执行get操作。

因此,您的调用将是:

inputField.type('abc123{enter}').should('have.value', 'abc123');

这只是一个设置问题,而不是实际解决方案,因为我知道您已经自己解决了该问题,但上述方法非常好,这样您就不必在同一字段上不断执行cy.get操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接