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
toHaveBeenCalled(..)
works with mock functions.To test that
ComponentA
is callingComponentB
, you create a mockComponentB
function and instantiate<ComponentA/>
:Give ComponentB an
aria-label
then in your test get any element with that label and useexpect(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.