blankface
blankface

Reputation: 6347

Cannot read property of null in jest test where child component is being mocked

I have 3 component structured as follows:

const Parent = () => {
    // this component uses hooks
    return (
        <div>
            Test
            <Child />
        </div>
    )
}

const Child = () => {
    // this component uses hooks
    return (
        <>
            Other content
            <Child2>
                {stuff}
            </Child2>
        </>
    )
}

const Child2 = () => {
    return <div>{children}</div>
}

In my test I'm mocking Child like:

import * as renderer from "react-test-renderer";

jest.doMock("./Child", () => () => <div>MockChild</div>);

describe("Snapshot", () => {
    it('renders correctly', () => {
        const tree = renderer
                        .create(<Parent />)
                        .toJSON();
        expect(tree).toMatchSnapshot();
    });
})

But upon running the test I'm getting this error: TypeError: Cannot read property 'children' of null.

Following the stacktrace I can see the error is from the children in Child2. My question is, why is jest mounting Child2 when I'm mocking Child in my test? Shouldn't it get disregarded? How can I solve this?

Upvotes: 1

Views: 10995

Answers (1)

Gianfranco Fertino
Gianfranco Fertino

Reputation: 632

jest.doMock is not hoisted

That is why you have to doMock first then import the Component below respectively.

import * as renderer from "react-test-renderer";

jest.doMock("./Child", () => () => <div>MockChild</div>);

// here is where you should import Parent
import Parent from './Parent';

describe("Snapshot", () => {
    it('renders correctly', () => {
        const tree = renderer
                        .create(<Parent />)
                        .toJSON();
        expect(tree).toMatchSnapshot();
    });
})

By the way, i recommend you to use the famous Enzyme instead of react-test-renderer. It has Shallow Rendering which exactly does what you wanted out of the box (mock every child component). It also offers Full render and static render.

Upvotes: 1

Related Questions