如何检查具有特定 class 的元素?

How do I check for an element with a certain class?

我的测试代码有

<div className="foo">
    {this.props.foo ? "foo!" : ""}
</div>

我想这样测试它:

it('shows no foo by default', () => {
    const wrapper = mount(
        <MyComponent/>
    );
    expect(wrapper).to.containMatchingElement(
        <div class="foo"/>
    );
});

但是,它永远找不到元素并且测试失败,即使输出显示我的元素:

AssertionError: expected <MyComponent /> to contain matching <div class="foo" />

    HTML:
    ...
    <div>
      <div class="foo"></div>
    </div>

如何断言具有给定 class 的 <div> 在输出中?

it('shows no foo by default', () => {
    const wrapper = shallow(
        <MyComponent />
    );
    expect(wrapper.find(".foo")).doTestHere(
        <div class="foo"/>
    );
});

试试这个。

你想尝试的方式应该是这样的

expect(wrapper.containsMatchingElement(<div class="foo"></div>)).to.equal(true);

你写的测试不完整

containsMatchingElement is a method of Enzyme but the expect是Chai的一种方法。

所以这两种方法不兼容:

expect(wrapper).to.containsMatchingElement(<div class="foo"></div>); // incompatible!

您应该像这样使用这些方法:

expect(wrapper.containsMatchingElement(<div class="foo"></div>)).to.be.true; // good