【问题标题】:Jest test hasClass() method returns false even when it is true开玩笑测试 hasClass() 方法即使为真也返回假
【发布时间】:2019-11-28 14:21:53
【问题描述】:

我已经为此苦苦挣扎了一段时间。它基本上归结为检查渲染的组件是否具有特定的类。我已经记录了它,只有当我在我正在搜索的特定类上调用 .find() 时它才会返回 true。这是我的输出:

test('Preview icon to be disabled', () => {
    console.warn(component
      .find('.preview-icon.is-disabled')
      .at(0)
      .html(),
    );

    console.warn(component
      .find('.preview-icon.is-disabled')
      .at(0)
      .hasClass('is-disabled'),
    );

    console.warn(component
      .find('.preview-icon')
      .at(0)
      .html(),
    );

    console.warn(component
      .find('.preview-icon')
      .at(0)
      .hasClass('is-disabled'),
    );

    expect(component
      .find('.preview-icon.is-disabled')
      .at(0)
      .exists(),
    ).toEqual(true);
  });

这个输出:

console.warn client/src/components/Preview.test.js:69
  <span class="toolbar-icon preview-icon is-disabled">Test Component</span>

console.warn client/src/components/Preview.test.js:75
  true

console.warn client/src/components/Preview.test.js:81
  <span class="toolbar-icon preview-icon is-disabled">Test Component</span>

console.warn client/src/components/Preview.test.js:87
  false

我的问题是,为什么我的第一组日志记录为真(当我搜索 .preview-icon.is-disabled 时)而不是当我只搜索 .preview-icon 时? HTML 匹配,并且在第二组日志记录 HTML 中,它显然具有 is-disabled 类。

我的实际期望语句是我目前的解决方法,但我觉得这个测试缺少一些东西。任何帮助是极大的赞赏。谢谢你。

【问题讨论】:

  • 你不会在寻找 component.find('.preview-icon').props('disabled') 。 ?
  • 不太确定会做什么,它返回一个 HTML 元素属性的对象,但不包含 disabled 的道具

标签: javascript reactjs jestjs enzyme


【解决方案1】:

我真的不知道为什么会发生这种情况,但我以前见过它并且有两个潜在的解决方法,您可以尝试解决这个问题。

第一个解决方法围绕着您的 .preview-icon 选择器,但不够具体。如果您使用span.preview-icon,它很可能会解决您的问题。

如果您使用mount 而不是shallow 来呈现您的组件,我将建议的第二种解决方法将起作用。您可以使用这样的验证来解决此问题:

expect(component.find('.preview-icon').get(0).getDOMNode().classList.contains('is-disabled')).toBeTruthy();

不过,正如我最初所说的,我真的没有确切的理由说明为什么会发生这种情况,尽管我过去也遇到过这种情况。希望我建议的一种(或两种)解决方法会有所帮助!

【讨论】:

  • 确认!第一个解决方法解决了这个问题!我也很高兴我不是唯一一个不时遇到这个问题的人。验证我并不像我想的那么疯狂。谢谢你的帮助。非常感谢!
猜你喜欢
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
  • 2020-02-06
  • 2020-03-25
  • 1970-01-01
  • 2021-02-11
相关资源
最近更新 更多