使用 className 反应酶 Jest 测试组件

Phi*_*cks 10 reactjs jestjs enzyme

我正在关注.find()的酶示例和这个 GitHub示例-jest示例以获得一个基本组件来测试和验证最外层元素是否className存在,我不明白为什么这没有通过:

// 反应组件

class VisitorShortcut extends Component {
//all the props & lifecycle hooks here
render() {
        return (
            <div className="visitor-shortcuts"> // <-- this className is being tested
                <div
                    onClick={e => e.stopPropagation()}
                    className="dropdown open"
                >
                    <ul
                        style={style}
                        ref="shortcutContainer"
                        className={"dropdown-menu "}
                    >
                        {results}
                    </ul>
                </div>
            </div>
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

// 测试文件

import React from "react";
import { shallow, mount } from "enzyme";
import VisitorShortcut from "../VisitorShortcut";

describe("Shortcuts", () => {
  test("The main Class exists", () => {
    expect(
        (<VisitorShortcut />).find(".visitor-shortcuts").length
    ).toBe(1);
  });
});
Run Code Online (Sandbox Code Playgroud)

// 输出

Expected value to be (using ===):
  1
Received:
  0
Run Code Online (Sandbox Code Playgroud)

如果我expect(wrapper.find('div.some-class')).to.have.length(3);按照 Enzyme docs切换到,输出是TypeError: Cannot read property 'have' of undefined

我相当确定我不需要使用mountAPI 而不是shallow

感谢您帮助澄清这一点。好像很基础...

Chi*_*dia 7

下面的代码对我有用

import React from "react";
import { shallow, mount } from "enzyme";
import { assert } from 'chai';
import VisitorShortcut from "../VisitorShortcut";    


describe("Shortcuts", () => {
  test("The main Class exists", () => {
    const wrapper = shallow(<VisitorShortcut />);
    const visitorShortcutsWrapper = wrapper.find('.visitor-shortcuts');
    assert.equal(visitorShortcutsWrapper.length, 1);
  });
});
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我正在使用assertfromchai包。

  • 当我`console.log(wrapper.find(".visitor-shortcuts"));`长度= 0 (2认同)

小智 6

根据 Enzyme 文档,您可以执行以下操作:

const wrapper = shallow(<VisitorShortcut />);
expect(wrapper.find("div.visitor-shortcuts").length).toBe(1)
Run Code Online (Sandbox Code Playgroud)