如何使用Enzyme Shallow测试传递给子组件的道具?

时间:2017-05-15 20:40:22

标签: reactjs testing material-ui enzyme

我在测试我的组件时遇到了问题,这个问题很简单地包装了Material-UI自动完成功能。在我的测试中,我想查看传递给的道具,但我的控制台语句是一个空对象。我使用Enzyme的浅层方法来渲染它。这是我的代码:

const underlineFocusStyle = {
    display: 'block',
    height: '100%',
    outline: 'none',
    position: 'relative', 
    padding: '0px', 
    width: '100%',
    border: 'none',
    backgroundColor: 'rgba(0, 0, 0, 0)',
    cursor: 'inherit',
    opacity: '1'
};

export class MyAutoComplete extends React.Component {
    render() {
        let { muiTheme, forceOpenOnFocus, ...propsToApply } = this.props;
        propsToApply.underlineFocusStyle = underlineFocusStyle;

        if (forceOpenOnFocus) {
            if (!propsToApply.filter) {
                propsToApply.filter = ((searchText, key) => {
                    return searchText === '' || AutoComplete.defaultProps.filter(searchText, key);
                });
            }
        }
        return <AutoComplete name={'autocomplete'} {...propsToApply} />;
    }
}

MyAutoComplete .propTypes = {
    muiTheme: PropTypes.object,
    forceOpenOnFocus: PropTypes.bool
}

export default muiThemeable()(MyAutoComplete );

我的测试:

describe('LLamasoftAutoComplete', () => {
    const muiTheme = getMuiTheme();
    const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});

    it('should pass in ', () => {
        const wrapper = shallowWithContext(
            <LLamasoftAutoComplete 
                muiTheme={muiTheme} 
                forceOpenOnFocus={true}
                dataSource={['One', 'Two', 'Three']} />
        );

        console.log(wrapper.find('AutoComplete').props()); //  is {}

        expect(true).toBe(false);
    });
});

1 个答案:

答案 0 :(得分:3)

正如您可能已经知道的那样,浅层渲染一个组件&#34;一层深度&#34;。另外,我假设您熟悉HOC的概念。(高阶组件)。您的MyAutoComplete包裹着muiThemeable HOC。如此浅的渲染只渲染muiThemeable,并且它不会渲染MyAutoComplete的渲染方法中的内容。因为那些在组件树中的深层不止一层。

为了避免这个问题,我们通常测试未修饰的组件;用HOC包装之前的原始组件。因此,我们需要从文件中导出装饰和未装饰的组件,将其中一个作为默认导出装饰,将未装饰的组件装饰为命名导出。

export default muiThemeable()(MyAutoComplete);
export { MyAutoComplete };

现在您可以导入未修饰的并测试它。在你的情况下,你实际上不需要用上下文来渲染它,因为你的组件中不再有muiThemeable,这取决于上下文。所以你的测试变得更简单了。

import { MyAutoComplete as LLamasoftAutoComplete} from './your/file/location'

describe('LLamasoftAutoComplete', () => {
    const muiTheme = getMuiTheme();

    it('should pass in ', () => {
        const wrapper = shallowWithContext(
            <LLamasoftAutoComplete 
                muiTheme={muiTheme} 
                forceOpenOnFocus={true}
                dataSource={['One', 'Two', 'Three']} />
        );

        console.log(wrapper.find('AutoComplete').props());

        expect(true).toBe(false);
    });
});

阅读此问题的答案以获取更多信息:How to test decorated React component with shallow rendering