我正在尝试使用 Cypress
(其中包含 mocha
,另外我正在使用 mocha-chai
)来检查短语中包含的一系列单词 NOT 。那是因为例如,我有三个 <div>
s 和我要检查
- div1 中的单词出现在 div1 中,但不出现在 div2 和 div3 中;
- div2 中的单词出现在 div2 中,但不出现在 div1 和 div3 中;
- div3 中的单词出现在 div3 中,但不出现在 div1 和 div2 中。
为此我使用了 .contain
和 .not.contain
但不幸的是他们找到了一些子字符串:
如果我有
// div1
<div>
...
The perfect professionist for you
</div>
// div2
<div>
...
Good professionists are ready here
</div>
我愿意
expect(div1).to.contain('professionist') // true
expext(div1).to.not.contain('professionists') // true
这很好,但是
expect(div2).to.contain('professionists') // true
expect(div2).to.not.contain('professionist') // false!
会失败。
有没有办法使用 cypress、mocha 或类似的东西来检查整个单词而不是子字符串?
最佳答案
单词边界:\b
更通用的是正则表达式 word boundary
cy.get('div').eq(1).invoke('text')
.then(div2Text => expect(div2Text).to.not.match(/\bprofessionist\b/)) // passes
或将单词传递到正则表达式中(注意 需要 \\b
才能正确翻译)
const word = 'professionist'
const regex = new RegExp(`\\b${word}\\b`)
cy.get('div').eq(1).invoke('text')
.then(div2Text => expect(div2Text).to.not.match(regex)) // passes
cy.get('div').eq(1).invoke('text')
.should('not.match', regex) // passes
你的pastebin
/// <reference types="cypress" />
before(() => {})
beforeEach(() => {
cy.viewport(2048, 1080)
})
describe('Test', () => {
it('simple test', () => {
let div = document.createElement('div')
let content = document.createTextNode('Good professionists are ready here')
div.appendChild(content)
try {
let word = 'professionist'
let regex = new RegExp(`\\b${word}\\b`)
expect(div.innerText).not.to.match(regex) // passes
word = 'professionists'
regex = new RegExp(`\\b${word}\\b`)
expect(div.innerText).to.match(regex) // passes
} catch (error) {
Cypress.log(error)
}
})
})
关于javascript - 使用 Cypress 和/或 mocha(或 mocha-chai)检查不包含单词但不包含子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713228/