如何使用Jest模拟包装器组件?

时间:2016-09-20 17:26:30

标签: reactjs material-ui jestjs

假设组件正在运行,我刚刚删除了无用的代码。在我要测试的组件中,我有这个:

import {Container} from "flux/utils";
import Dialog from "material-ui/Dialog";
import React from "react";
...

class Component extends React.Component {
    state;

    static calculateState() {
        return {
            ...
        };
    }

    static getStores() {
        return [...];
    }

    ...

    render() {
        var actions = [...];

        return <Dialog
            actions={actions}
            open={this.state.open}
            title="foo"
            ...
        >
            <form ...>
                {/* My inputs and their values are according to the state. */}
            </form>
        </Dialog>;
    }
}

const MyComponent = Container.create(Component);

export default MyComponent;

在UI中,输入及其值正在起作用。但是,当我使用Jest时,它不是。

jest.mock('react-dom');
jest.mock('material-ui/Dialog', () => 'Dialog');

import Dispatcher from "../../dispatcher/Dispatcher";
import MyComponent from "../MyComponent";
import React from "react";
import Renderer from "react-test-renderer";

describe('MyComponent', () => {
    it('creates', () => {
        const component = Renderer.create(<MyComponent/>);
        let tree = component.toJSON();
        expect(tree).toMatchSnapshot();

        Dispatcher.dispatch({
            action: 'myComponent/open'
        });
        tree = component.toJSON();
        expect(tree).toMatchSnapshot();

        tree.children[0].children[1].children[0].props.onChange(undefined, undefined, 'john');
        tree = component.toJSON();
        expect(tree).toMatchSnapshot();
    });
});

第一张快照很好。第二个快照也很好,开放属性正在改变。但是,当我触发输入的onChange时,组件状态正在更新,一切都很好...但是当我做最后一个快照时,如果输入值不同(状态很好),则子项仍然相同更新,确认)。

我知道这是由于Dialog。如果我从组件类中删除它,组件按预期工作......那么我应该如何声明模拟?

这是我的最后一次尝试:

jest.mock('material-ui/Dialog', () => {
    var React = require("react");

    return class extends React.Component {
        shouldComponentUpdate() {
            return true;
        }

        render() {
            var {children, ...rest} = this.props;

            return children;
        }
    }
});

孩子们仍然是一样的:(

0 个答案:

没有答案