代码之家  ›  专栏  ›  技术社区  ›  kamlesh paliwal

如何使用react test renderer和jest测试包含嵌套组件的react组件?

  •  0
  • kamlesh paliwal  · 技术社区  · 7 年前

    以下是我为测试组件而编写的代码:

    import React from 'react';
    import renderer from 'react-test-renderer';
    import sinon from 'sinon';
    import { clone } from 'lodash';
    import { ProfileImageSelect } from 
    '../../../../components/settings/ProfileImageSelect';
    
    const userInfo = {
        first_name: 'test_first_name',
        last_name: 'test_last_name'
    };
    
    describe('<ProfileImageSelect />', () => {
        let onClose;
        let onSelect;
        let socialLogins;
    
        beforeEach(() => {
            socialLogins = {
                facebook: {
                    id: '187416164',
                    identifier: 'adams_facebook',
                    full_name: 'Eric Adams',
                    profile_pic: 'profile_pic_facebook.jpeg',
                    expired: false
                },
                twitter: {
                    full_name: 'Eric Adams',
                    id: '187416164',
                    identifier: 'adams_ea',
                    profile_pic: 'https://pbs.twimg.com/profile_images/707586445427380226/5uETA8fs.jpg',
                    expired: false
                },
                linkedin: {
                    full_name: 'Eric Adams',
                    id: '8vN6Da_RJJ',
                    identifier: 'adams.ea@gmail.com',
                    profile_pic:
                        'https://media.licdn.com/dms/image/C5603AQFfn5Ko5IS1NQ/profile-displayphoto-shrink_100_100/0?e=1549497600&v=beta&t=11m5mirEr_R2gf3OOfh3zHTL3Xe2ImrxcZ7l7ebLDa0',
                    expired: false
                }
            };
            onClose = sinon.stub();
            onSelect = sinon.stub();
        });
    
        it('calls onClose on the props on click of cancel link ', () => {
            const connected = clone(socialLogins, true);
            const testRenderer = renderer.create(
                <ProfileImageSelect
                    onSelect={onSelect}
                    onClose={onClose}
                    socialLogins={connected}
                    userInfo={userInfo}
                />
            );
            const root = testRenderer.root;
            root.findByProps({ className: 'cancel' }).props.onPress();
            expect(onClose.called).toEqual(true);
        });
    });
    

    但它显示了一个错误:

    我知道我可以使用'react test renderer/shallow'进行浅渲染,但它不允许我像酶一样从DOM中找到任何节点。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Dima Vishnyakov    7 年前

    您可以手动定义模拟商店,并将其作为一个道具传递给组件。不幸的是,它只适用于指定的组件,如果你想更深入,你必须使用 redux-mock-store 或者编写自己的上下文提供程序。

        2
  •  0
  •   kboul    7 年前

    可以为添加其他默认导出

    ProfileImageSelect (类)没有连接的,

    import  ProfileImageSelect  from 
    '../../../../components/settings/ProfileImageSelect';
    

    这样你就运行了一个浅层单元测试。 仅仅为了测试而添加代码或公开对象通常不是最佳实践。