【问题标题】:Jest throwing render error when loading functional child component加载功能性子组件时开玩笑抛出渲染错误
【发布时间】:2020-12-15 20:01:19
【问题描述】:

在为父组件运行测试文件时收到Error: Uncaught [Error: Child(...): Nothing was returned from render

这些是相关文件

/components/Page/Children/Child.js

import React from "react"

export default function Child() {
  return <div>abc</div>
}

/components/Page/Children/index.js

export { default } from "./Child"

/components/Page/Parent.js

import React from "react"
import Child from "./Children"

export default class Parent extends React.Component {
  constructor(props) {
    super(props)
  }

  render() {
    return <Child />
  }
}

/components/Page/_tests_/Parent.spec.js

import Parent from "../Parent"

jest.mock("../Children")

describe("<Parent/>", () => {
  let wrapper
  let props = ...

  describe("render", () => {
    it("renders", () => {
       wrapper = mount(<Parent props={props} />)
       expect(wrapper).toMatchSnapshot()
    })
  })

将 Child.js 文件更改为 react 类组件(如下更新)可以解决问题,但我不明白为什么会这样。

/components/Page/Children/Child.js

import React from "react"

export default class Child extends React.Component {
  render() {
    return <div>abc</div>
  }
}

【问题讨论】:

标签: javascript reactjs jestjs


【解决方案1】:

发生此错误的原因是您正在模拟 ./Children 模块并且您没有提供模拟的 Child 组件。所以,如果你想模拟Child 组件,你需要提供一个return statement

例如

Parent.spec.js:

import React from 'react';
import Parent from './Parent';

jest.mock('./Children', () => {
  return jest.fn(() => <div>mocked child</div>);
});

describe('<Parent/>', () => {
  let wrapper;
  let props = {};

  describe('render', () => {
    it('renders', () => {
      wrapper = mount(<Parent props={props} />);
      expect(wrapper).toMatchSnapshot();
    });
  });
});

单元测试结果:

 PASS  src/stackoverflow/63607465/Page/Parent.spec.js
  <Parent/>
    render
      ✓ renders (37ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   1 passed, 1 total
Time:        2.792s, estimated 3s

快照:

// Jest Snapshot v1, 

exports[`<Parent/> render renders 1`] = `
<Parent
  props={Object {}}
>
  <mockConstructor>
    <div>
      mocked child
    </div>
  </mockConstructor>
</Parent>
`;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 2018-09-27
    • 2021-07-13
    • 2017-05-20
    • 2022-08-10
    • 2018-07-20
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多