【问题标题】:Enzyme not finding text in a div that is there酶在存在的 div 中找不到文本
【发布时间】:2020-09-08 07:53:09
【问题描述】:

我有一个测试,我在一系列 Material-UI 卡片中呈现了一些文本。我在 JSON 数组中为每张卡片提供数据,其中每个对象看起来像这样

  {
        projectName: 'Project1',
        crc: 11305,
        dateCreated: '1/1/2020',
        createdBy: 'A. Bloggs',
        lastModified: '22/2/2020'
  }

在我的酶测试中,我找到了所有卡片,然后使用以下代码确保每条 JSON 数据都已在 Card 中呈现。

const verifyThatAllCardDataIsRenderedCorrectly = ( cardsFound, dataItemsSupplied) => {
    dataItemsSupplied.forEach((dataItem, currCardIndex) => {
        for(let key in dataItem){
            if(key !== 'id'){
                console.log("Comparing CARD CONTENT ===>"+cardsFound.at(currCardIndex).debug() + " WITH =====> "+dataItem[key]);
                expect(cardsFound.at(currCardIndex).contains(dataItem[key])).toEqual(true);
            }
        }
    });
};

当测试失败时,我查看调试输出 Card 中的相关部分 cardsFound.at(currCardIndex).debug() ,它看起来像这样:

 <div className="makeStyles-projectPropertiesGridContainer-348">
    <div className="makeStyles-projectPropertyName-349">
      CRC
    </div>
    <div className="makeStyles-projectPropertyValue-350">
      11305
    </div>
</div>

dataItem[key] 的值是11305 那么为什么断言 expect(cardsFound.at(currCardIndex).contains(dataItem[key])).toEqual(true) 失败??

projectName 属性的先前断言匹配并通过!

【问题讨论】:

  • expect(cardsFound.at(currCardIndex).text()).toContain(dataItem[key]) 应该可以工作
  • 确实如此!太感谢了。也许您可以将您的评论作为答案,以便我可以将其标记为已接受的答案?

标签: javascript reactjs jestjs material-ui enzyme


【解决方案1】:

由于您只想检查元素中是否存在文本,您可以使用 text()toContain

const verifyThatAllCardDataIsRenderedCorrectly = ( cardsFound, dataItemsSupplied) => {
    dataItemsSupplied.forEach((dataItem, currCardIndex) => {
        for(let key in dataItem){
            if(key !== 'id'){
                console.log("Comparing CARD CONTENT ===>"+cardsFound.at(currCardIndex).debug() + " WITH =====> "+dataItem[key]);
                expect(cardsFound.at(currCardIndex).text()).toContain(dataItem[key])
            }
        }
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    相关资源
    最近更新 更多