英文:
add regex as parameter in a Cypress cucumber step definition
问题
我想使用Cypress来检查这一整行,但提到的时间可能会有所变化。我可以使用正则表达式吗?如果可以,应该如何做?谢谢。
英文:
I want to check this complete line with Cypress but the time mentioned can vary. Can I use a regex for this and how do i do this? Thanks
Then I verify the AL notification list contains unread item "some text 03:39 some more text"
答案1
得分: 3
我建议你将正则表达式的实现隐藏在步骤代码内部,以避免生成难看的报告。
Then('I verify the AL notification list contains unread item {string}', (item) => {
const re = new RegExp(item.replace('99:99', '\\d{2}:\\d{2}'))
cy.get(select).invoke('text').should('match', re)
})
英文:
I suggest you hide the regex implementation inside the step code, to avoid ugly reports.
Then I verify the AL notification list contains unread item "some text 99:99 some more text"
Then('I verify the AL notification list contains unread item {string}', (item) => {
const re = new RegExp(item.replace('99:99', '\d{2}:\d{2}'))
cy.get(select).invoke('text').should('match', re)
})
</details>
# 答案2
**得分**: 1
在你的特性文件中:
Then I verify the AL notification list contains unread item ".(\d{2}:\d{2}).";
可以尝试使用正则表达式 `".*(\d{2}:\d{2}).*"` 来匹配你的文本 `"some text 03:39 some more text"`,链接在这里:https://regexr.com/7esif
在你的步骤定义中:
```javascript
Then('I verify the AL notification list contains unread item {string}', (regexString) => {
const regexSearch = new RegExp(regexString, "g"); // 使用 RegExp 对象构造函数将字符串转换为正则表达式
cy.get('div or id ').invoke('text').should('match', regexSearch); // 获取元素文本然后使用 match(RegExp) 进行匹配
})
解释:
- 在你的特性文件中将正则表达式作为参数传递。
- 使用 RegExp 对象构造函数将字符串转换为正则表达式,详情请参考:https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp
- 获取元素文本,然后使用
match(RegExp)
进行匹配,详情请参考:https://docs.cypress.io/guides/references/assertions#Chai
英文:
In your feature file:
Then I verify the AL notification list contains unread item ".*(\d{2}:\d{2}).*"
Can try the regex ".*(\d{2}:\d{2}).*" to match with your text "some text 03:39 some more text" here: https://regexr.com/7esif
In your step definition:
Then('I verify the AL notification list contains unread item {string}', (regexString) => {
const regexSearch = new RegExp(regexString, "g"); // convert string to regex by using RegExp object constructor
cy.get('div or id ').invoke('text').should('match', regexSearch); // get element text then match with regex using match(RegExp)
})
Explanation
- pass regex as parameter in your feature file
- convert string to regex by using RegExp object constructor : https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp
- get element text then match with regex using "match(RegExp)" https://docs.cypress.io/guides/references/assertions#Chai
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论