3

我正在构建一个 HoC,以便轻松创建可选择的表行。我正在尝试编写测试以确保它使用正确传递的道具呈现包装的组件。不幸的是,我无法让我的测试正常工作,因为酶似乎没有将所有成分都渲染出来(或者,更有可能的是,我在做一些有点傻的事情)。

霍克

import React, { PropTypes, Component } from "react";
import { omit } from "lodash/fp";

const propsFilter = omit(["onSelect"]);

export default function selectable(onSelect, isSelected) {
    return (component) => {
        const wrappedName = component.displayName || component.name || "Component";
        const displayName = `Selectable(${wrappedName})`;
        const onClick = () => onSelect && onSelect(!isSelected);

        class SelectableWrapper extends Component {
            render() {
                return <component onClick={ onClick } { ...propsFilter(this.props) } />;
            }
        }

        SelectableWrapper.displayName = displayName;
        SelectableWrapper.propTypes = Object.assign({
            onSelect: PropTypes.func,
            isSelected: PropTypes.bool,
        }, component.propTypes);

        return SelectableWrapper;
    };
}

测试

/* eslint-env mocha */

"use strict";

import React from "react";
import { expect } from "chai";
import { spy } from "sinon";

import { mount } from "enzyme";

import selectable from "../../../src/js/components/tables/selectable";

describe("<SelectableHOC />", () => {
    let onSelect, isSelected;

    const TestElement = () => <p className="test">Hi</p>;

    const el = () => selectable(onSelect, isSelected)(TestElement);
    beforeEach("setup spy", () => onSelect = new spy());

    it("renders the wrapped component, passing through props", () => {
        const hoc = el();
        const wrapper = mount(<hoc name="foo" />);
        expect(wrapper).to.contain("p.test");
    });

    it("doesn't pass through onSelect");
    it("sets onClick on the child component, which triggers onSelect");
});

当我wrapper.debug()在测试中尝试时,我得到了<hoc data-reactroot="" name="foo"></hoc>.

测试的输出(失败)是:

  1) <SelectableHOC /> renders the wrapped component, passing through props:
     AssertionError: expected <HTMLUnknownElement /> to contain p.test

     HTML:

     <hoc data-reactroot="" name="foo"></hoc>
      at Context.<anonymous> (test/components/tables/selectable.spec.js:43:39)
4

2 回答 2

1

您的组件的名称是小写的,在 JSX 中以小写名称开头的名称被认为是 HTML 标签,而不是自定义组件。因此,您需要将组件名称大写。

另外,我建议您将组件的名称更改为更有意义的名称,以避免与React.Component.

您可以在官方反应文档这个问题中阅读更多相关信息。

于 2017-07-21T09:49:45.387 回答
0

您必须找到包装的组件并检查其上的道具

const elWrapper = wrapper.find('TestElement');
expect(elWrapper.prop('onClick').to.not.equal(null);
expect(elWrapper.prop('onSelect').to.equal(undefined);
于 2017-07-21T04:23:14.293 回答