0

I am getting Error: Uncaught [Error: Child(...): Nothing was returned from render when running a test file for the Parent component.

These are the relevant files

/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()
    })
  })

changing the Child.js file to a react class component (as updated below) resolves the issue but I do not understand why that would be.

/components/Page/Children/Child.js

import React from "react"

export default class Child extends React.Component {
  render() {
    return <div>abc</div>
  }
}
Lin Du
  • 88,126
  • 95
  • 281
  • 483
tausabao
  • 247
  • 1
  • 3
  • 11

1 Answers1

0

The reason why this error happened is you are mocking the ./Children module and you didn't provide a mocked Child component. So, if you want to mock the Child component, you need to provide a return statement.

E.g.

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

unit test result:

 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

snapshot:

// Jest Snapshot v1, 

exports[`<Parent/> render renders 1`] = `
<Parent
  props={Object {}}
>
  <mockConstructor>
    <div>
      mocked child
    </div>
  </mockConstructor>
</Parent>
`;
Lin Du
  • 88,126
  • 95
  • 281
  • 483