使用className反应Enzyme Jest测试组件

时间:2018-03-21 17:20:46

标签: reactjs enzyme jest

我是 在.find()和GitHub enzyme-example-jest示例的Enzyme示例之后,为了获得测试和验证最外层元素className的基本组件,我不明白为什么这不会通过:

// REACT COMPONENT

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>
        );
    }
}

// TEST FILE

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);
  });
});

// OUTPUT

Expected value to be (using ===):
  1
Received:
  0

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

我很确定我不需要使用mount API代替shallow

感谢您帮助澄清这一点。看起来很基本......

5 个答案:

答案 0 :(得分:2)

以下代码对我有用

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);
  });
});

顺便说一下,我使用assert包中的chai

答案 1 :(得分:1)

我使用chai,它有效。

import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import App from './App';

describe('<App />', () => {
  const wrapper = shallow(<App />);

  it('should have an App class', () => {
    expect(wrapper.find('.App')).to.have.length(1);
  });
});

答案 2 :(得分:1)

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

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

答案 3 :(得分:0)

事实证明,我的完整代码库有一些返回null的东西,这就是为什么node.length = 0.感谢你对此进行调查。

答案 4 :(得分:0)

这用于检查Jest中的元素是否有两个子元素

expect(wrapper.find('.parent-class').getElements().length).toEqual(2)