具有组件的测试已渲染

问题描述 投票:0回答:1

我正在将Jest与Enzyme一起用于单元测试。我有一个根据媒体类型呈现组件的组件。在单元测试中,我正在检查是否已渲染适当的组件。

我的组件

const getComponent = {
 'image': ImageComp,
 'video': VideoComp,
 'other': DocumentComp
}

const MediaDisplay =  (props) =>  {
    let { assetInfo } = props;
    let source = assetInfo.assetUrl;
    const PreviewComponent = getComponent[assetInfo.type];
    return ( <div>
        {source && <PreviewComponent assetInfo={assetInfo} />}
        </div>
    );
}
  

在单元测试中,

import React from 'react';
import MediaDisplay from './../MediaDisplay';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });

describe('<MediaDisplay/>', () => {
  it('should render Image component when asset type is image', () => {
    const mockAssetInfo = {
        assetUrl:'https://example.com/image001.jpg',
        type:'image'

    };
    const component = mount(<MediaDisplay assetInfo={mockAssetInfo} />);
    expect(component).toMatchSnapshot();
  });
});

我认为我没有正确编写测试用例。有人可以帮我写这个测试用例吗?

P.S-我在图像组件内部有一个单独的测试用例,用于检查是否渲染了图像,我正在检查标记是否具有长度。

提前感谢一吨。

reactjs enzyme jest
1个回答
0
投票

我认为您的测试没有执行应该进行的测试,因为您的案例告诉您,当资产类型为图像时,它应该呈现Image组件,但是如果您正在使用的话,您只是在检查该组件是否与快照匹配安装后,您应该能够看到子组件的内容,因此,例如,如果PreviewComponent根据传递的道具显示不同的内容,则可以测试这些行为。或者,如果您只想检查assetInfo.type是否为'image',则可以随时执行以下操作:

  it("contains an assetInfo image type", () => {
   expect(component.prop("assetInfo").type).toEqual(mockAssetInfo.type);
  });

如果您只想检查孩子是否存在并成功渲染,则可以使用shallow代替mount并执行此操作:

import PreviewComponent from "your-component-route"

describe("renders a PreviewComponent", () => {
 beforeAll(() => {
  const mockAssetInfo = {
    assetUrl:'https://example.com/image001.jpg',
    type:'image'

  };
  const component = shallow(<MediaDisplay assetInfo={mockAssetInfo} />);
 });

 it("wraps a PreviewComponent component", () => {
  expect(component.find(PreviewComponent).length).toBe(1);
 });
});
© www.soinside.com 2019 - 2024. All rights reserved.