首页 > 解决方案 > 使用 Enzyme 进行测试时如何在渲染道具中渲染元素

问题描述

我有一个具有这种结构的组件

return <Element>
            {(a, b): React.ReactElement => (
               ...some elements here
         )}
        </Element>;

当我测试它时,我得到了这个debug

<Element>
   [function]
 </Element>

我的问题是进入这个函数来检查它返回的元素的通常方法是什么?

我的测试

import React from 'react';

import {createShallow} from '@material-ui/core/test-utils';

import Component from './Component';

let shallow;

function setup() {
    const props = {};

    const wrapper = shallow(<Component {...props} />);

    return {
        props,
        wrapper,
    };
}

beforeAll(() => {
    shallow = createShallow({ dive: true });
});

describe('Components', () => {
    describe('Element', () => {
        it('Should render self', () => {
            const {wrapper, props} = setup();

            console.log(wrapper.debug())

            expect(wrapper.exists()).toBeTruthy();
        });
    });
});

标签: reactjsjestjsenzyme

解决方案


有两种解决方案:

  1. 使用wrapper.dive()orwrapper.shallow()会导致您ShallowWrapper渲染顶级组件的子组件。但是,我完全不建议使用shallow它,因为它有很多问题,而您刚刚经历过一个问题 - 它不会渲染所有内容。
  2. 使用mount而不是,shallow您将默认呈现您的子函数。

推荐阅读