首页 > 解决方案 > 如何使用 react-test-renderer 和 jest 测试包含嵌套组件的反应组件,这些组件是连接组件?

问题描述

实际上,我正在使用 react-test-render 和 jest 在 react-native 中编写测试用例?我有一个需要测试的组件,该组件包含嵌套组件,它们是连接组件。以下是我为测试组件而编写的代码:

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);
    });
});

但它告诉我一个错误说:

不变违规:在“Connect(SocialServiceProfileImage)”的上下文或道具中找不到“商店”。要么将根组件包装在 a 中,要么将“store”作为道具显式传递给“Connect(SocialServiceProfileImage)”。

我知道我可以使用“react-test-renderer/shallow”进行浅渲染,但它不允许我像 Enzyme 那样从 DOM 中找到任何节点。谁能帮我这个?。我没有酶,也不想用于 react-redux-mock-store。

标签: react-nativejestjsreact-test-renderer

解决方案


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


推荐阅读