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

How do I test props passed to child component using Enzyme Shallow?

我在测试我的组件时遇到问题,该组件薄薄地包装了 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);
    });
});

您可能已经知道,浅层渲染组件 "one level deep"。此外,我假设您熟悉 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);
    });
});

阅读此问题的答案以获取更多信息: