使用 Cypress 根据后端的值有条件地断言 DOM 中的元素值?
尝试使用我的 React 应用程序进行 Cypress 测试。
我正在从后端检索具有属性 expirationDate 的对象。它是一个格式为 YYYYMMDD 的整数。在 组件中相应的前端中,它呈现为 YYYY-MM-DD 字符串。
但是,该对象可以选择根本没有到期日期,而是表示为 -1 或 -2 属性。这在 中显示为空字符串 ''。
因此我需要有条件地检查该值。我该如何使用 Cypress 来做到这一点?
我现在最接近的是
cy.get('#input-expiration-date').should('have.value', expirationDate || '')
但这并不是对上述条件的准确测试。
Trying to do Cypress Testing with my React app.
I'm retrieving an object with an attribute expirationDate from the backend. It's an integer with format YYYYMMDD. In my corresponding frontend in the <input>
component, it's rendered as an YYYY-MM-DD string.
However the object may optionally not have an expiration date at all, which is instead represented as the attribute being -1 or -2. This is presented as an empty string '' in the <input>
.
I thus need to conditionally check the value. How do I go about doing this with Cypress?
Closest I have right now is
cy.get('#input-expiration-date').should('have.value', expirationDate || '')
But this is not really an accurate test of the above conditions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
条件测试可以按如下方式完成,但这是不好的做法。
测试的运行速度快于从服务器获取值的速度。
您可以通过使用 cy.intercept() 等待对象获取并然后进行条件检查来避免此问题。
Conditional testing can be done as follows, but this is bad practice.
The test runs faster than the value can be fetched from the server.
You can avoid the issue by waiting for the object fetch with
cy.intercept()
and do the conditional check then.您可以使用 Chai 方法 oneOf() 。
Cypress 在内部使用 Chai,因此表达式在
.should()
内部工作。直接使用 Chai
There a Chai method oneOf() you can use.
Cypress uses Chai internally, so the expression works inside
.should()
.Using Chai directly
使用 cy.intercept() 获取来自后端的值。
一般方法(可能会根据响应模式而有所不同):
您还可以更进一步,通过存根消除任何后端变化
Use
cy.intercept()
to get the value coming from the back-end.General approach (may vary depending on response pattern):
You can also go one step further and eliminate any backend variation by stubbing
你可以这样做:
you can do:
或者,如果您想检查并根据该值进一步执行一些操作,您可以执行以下操作:
Or if you want to check and further do some actions based on the value, you can do something like this: