javascript - 使用 Cypress 和/或 mocha(或 mocha-chai)检查不包含单词但不包含子字符串

标签 javascript mocha.js cypress

我正在尝试使用 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)
    }
  })
})

enter image description here

关于javascript - 使用 Cypress 和/或 mocha(或 mocha-chai)检查不包含单词但不包含子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713228/

相关文章:

javascript - Node.js - 如果不满足目标值,如何默认为特定值

node.js - 我可以使 Chai 的 Expect.to.not.throw 同步吗?

typescript - 从 CLI 执行时,Cypress 环境变量会选择多个值。如何在Cypress测试中传递多个环境变量?

javascript - Cypress 测试 Material-UI 日期选择器不适用于 Github 操作

javascript - 为什么我的 mocha/should Array throw 测试失败了?

javascript - 如何使用 Cypress 在编辑器中选择文本

Javascript 表单验证 : custom error message

javascript - 在不超过特定值的对象数组中找到最大值 - Javascript

javascript - 获取 URI 的路径部分

node.js - Mocha 测试,链接 super 测试请求