I am trying to using Cypress (which contains mocha, plus I am using mocha-chai) to check for a series of words NOT included in a phrase. That is because for example, I have three <div>s and I want to check
To do that I'm using .contain and .not.contain but unluckily they find some substrings:
if I have
// div1
<div>
...
The perfect professionist for you
</div>
// div2
<div>
...
Good professionists are ready here
</div>
I do
expect(div1).to.contain('professionist') // true
expext(div1).to.not.contain('professionists') // true
this is fine, but
expect(div2).to.contain('professionists') // true
expect(div2).to.not.contain('professionist') // false!
will fail.
Is there a way using cypress, mocha or anything similar to do a check on entire word but not substring?
You can use a regex to do that. For assertion, you have to use match().
var regexValue = "(?<!\S)word(?!\S)"
var actualRegexValue = new RegExp(regexValue.replace("word", "professionist"))
cy.get('div2').invoke('text').then((text) => {
expect(text).to.match(actualRegexValue)
})
Your regex /(?<!\S)professionist(?!\S)/ will only search for the string professionist in the sentence and not anything else not even professionists.
More general is regex word boundary
cy.get('div').eq(1).invoke('text')
.then(div2Text => expect(div2Text).to.not.match(/\bprofessionist\b/)) // passes
or passing the word into the regex (note requires \\b for propper translation)
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
/// <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)
}
})
})