1

So I’ve read posts and watched tutorials on using Enzyme to test that a nested component is rendered with the correct props. I’ve also read the seemingly contradictory recommendation in the official react testing docs guidelines against testing component instances. This leaves me confused as to whether or not it is helpful to test whether nested components are rendered with the correct props. enter image description here

As an example, here is a component with a nested component where the child component takes various prop values depending on the parent's props. Would it make sense here to test the props of the nested Decision components?

enter image description here

/* Parent Component */

import Decision from "./Decision";

interface BookProps {
    age: number;
    boring: boolean;
    chapters: number[];
}

const Book = ({ age, boring, chapters }: BookProps) => {
    if (age < 10) {
        return (<Decision
            bookDescription={chapters.length > 0 ? 'a chapter book' : 'prose'}
            shouldAssignToStudents={boring && chapters.length > 10}
        />)
    } else {
        return (<Decision
            bookDescription={'old'}
            shouldAssignToStudents={false}
        />)
    }
}
export default Book;

/* Child Component */

interface DecisionProps {
    bookDescription: string;
    shouldAssignToStudents: boolean
}
const Decision = ({ bookDescription, shouldAssignToStudents }: DecisionProps) => {
    return (<div>
        {`This book is ${bookDescription} and the 
        students ${shouldAssignToStudents && 'do not '} need to read it`}
    </div>);
}

export default Decision;
GNG
  • 1,341
  • 2
  • 23
  • 50

1 Answers1

0

You don't need to test that a component is called with certain props, you need to test that the output is what you'd expect given some input.

e.g. a single test case could be passing an age less than 10 to Book would produce a certain HTML/text output. Remember a component is just a function at the end of the day, and the best true unit test would test that inputs produce outputs.

For testing Decision directly its even more simple really, you can call it with different values of shouldAssignStudents and confirm the output is what you'd expect. Anything that involves branching logic to determine output can be tested directly.

the official react testing docs guidelines against testing component instances

Yes and actually thats a reason Enzyme has fallen out of favor. Its API's focus on testing component instances which is not a good way of testing components. You can test with Enzyme the idiomatic way but you'll end up ignoring the props() APIs, and end up exclusively testing with APIs like .containsAnyMatchingElements,

If you are open to it you should consider React Testing Library instead. Its APIs are focussed on testing component output rather than testing component instances themselves.

Pure Function
  • 2,129
  • 1
  • 22
  • 31