首页 > 解决方案 > 使用 switch 语句根据类型呈现各种 HTML 元素的 React 组件的 Jest 测试不断失败

问题描述

我有一个 React 组件,它接受一个数组并遍历每个节点,根据数组中找到的类型设置和呈现 HTML 元素。

我的一切运行正常,现在我正在尝试使用 Jest 编写一个测试来检查:

  1. 组件在接收到空数组时不渲染任何内容
  2. 组件在收到填充数组时根据类型呈现适当的 HTML 元素

我对 Jest 和测试比较陌生,我不确定如何编写测试来检查是否呈现了适当的元素。我的空检查测试也一直失败,并显示以下错误消息:

 FAIL  src/components/RenderTextComponent.spec.js
  ● <RenderTextComponent /> › renders null for empty sections array

    expect(received).toEqual(expected)

    Expected value to equal:
      null
    Received:
      <RenderTextComponent />

    Difference:

      Comparing two different types of values. Expected null but received object.

      27 |
      28 |   it('renders null for empty sections array', () => {
    > 29 |     expect(<RenderTextComponent {...emptySections} />).toEqual(null)
         |                                                  ^
      30 |   })
      31 |
      32 |   it('renders', () => {

      at Object.it (src/components/RenderTextComponent.spec.js:29:50)

这是我的测试文件:

import React from 'react';
import { shallow } from 'enzyme'
import RenderTextComponent from './RenderTextComponent'


describe('<RenderTextComponent />', () => {
  let wrapper;

  const sections = {}

  const populatedSections = [
    {
    type: "subtitle",
    text: ["This is a really cool subtitle filled with words of wonder"]
    },
    {
      type: "body",
      text: ["This is an even cooler sentence that shows up as a paragraph.", "And this is a second sentence that shows up as a second paragraph."]
  }
]

  const emptySections = []

  beforeEach(() => {
    wrapper = shallow(<RenderTextComponent {...sections} />);
  });

  it('renders null for empty sections array', () => {
    expect(<RenderTextComponent {...emptySections} />).toEqual(null)
  })

  it('renders', () => {
    expect(<RenderTextComponent {...populatedSections} />).toEqual(expect.anything())
  })

})

这是我正在测试的原始组件:

import React from "react";
import styled from "styled-components";

function renderElements(sections) {
  const elements = [];

  if (!sections) return null;

  sections.map((section) => {
    switch (section.type) {
      case "title":
        return elements.push(
          section.text.map((string) => <Title>{string}</Title>)
        );
      case "subtitle":
        return elements.push(
          section.text.map((string) => <Subtitle>{string}</Subtitle>)
        );
      case "body":
        return elements.push(
          section.text.map((string) => <Body>{string}</Body>)
        );
      default:
        return null;
    }
  });
  return elements;
}

const RenderTextComponent = ({ sections }) => {
  return <>{renderElements(sections)}</>;
};

export default RenderTextComponent;

const Title = styled.h1`
  font-size: 28px;
`;

const Subtitle = styled.h4`
  font-size: 24px;
`;

const Body = styled.p`
  font-size: 18px;
`

标签: javascriptreactjsjestjsenzyme

解决方案


当您null从组件返回时,React.createElement仍会创建一个元素。如果不检查结果标记,就无法真正判断它是否不会呈现任何内容。

例如,此代码将在控制台中为您提供适当的反应元素,而不是null

function EmptyComponent() {
  return null
}

console.log(<Component/>);

您可以尝试将您的组件渲染到 jsdom 中并检查快照或预期标记(或两者)

编辑:代替 jsdom 可以渲染为字符串。在这种情况下,您应该得到空字符串


推荐阅读