skip to Main Content

For example,

ComponentA.tsx:

const ComponentA = () => {
    return (
        <>
        <ComponentB/>
        </>
    )
}

ComponentA.test.tsx

describe("ComponentA", () => {
    it("Calls ComponentB in render", () => {
        render(<ComponentA/>);
        const componentB = <ComponentB/>;
        expect(componentB).toHaveBeenCalledTimes(1);
    });
});

Tried the above but the test still failed. I was hoping something similar to that would work, and I tried other variations of the above, but still didn’t get to the passing test. There was once instance where I ran something similar to this with a waitFor around the expect and it passed, but the passing test wasn’t correctly passing.

2

Answers


  1. toHaveBeenCalled(..) works with mock functions.

    To test that ComponentA is calling ComponentB, you create a mock ComponentB function and instantiate <ComponentA/>:

    const ComponentA = () => {
        return (
            <>
            <ComponentB/>
            </>
        )
    }
    
    // Create mock function
    const ComponentB = jest.fn();
    
    describe("ComponentA", () => {
        it("Calls ComponentB in render", () => {
            render(<ComponentA/>);
            expect(ComponentB).toHaveBeenCalledTimes(1);
        });
    });
    
    Login or Signup to reply.
  2. Give ComponentB an aria-label then in your test get any element with that label and use expect(element).toBeInTheDocument(); or something to that effect.

    This is good practice for accessibility by the way. Because if elements are as supportive of accessibility as they should be, they should also have methods of easily identifying whether or not they are in the DOM. That’s one of the purposes of the test case you are writing. Some lint rules can even be added to your environment to check for accessibility.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search