Ok, I couldn't find a better title for my question.
The fact is that I have something that looks like the following:
import React from "react";
import AppContext from "context";
const Component = () => {
const { myMethod } = React.useContext(AppContext);
React.useEffect(() => {
if (myMethod) {
myMethod();
}
});
return (<bla bla />);
}
export default Component;
and in my test, I'm doing:
import { render } from "@testing-library/react";
import Component from "./index";
import AppContext from "context";
describe("Test the Component component", () => {
it("should call the myMethod method", () => {
const myMethod = jest.fn();
render(
<AppContext.Provider value={{ myMethod }}>
<Component />
</AppContext.Provider>
);
expect(myMethod).toBeCalled(); // Working!
});
it("shouldn't call the myMethod method", () => {
const myMethod = undefined;
render(
<AppContext.Provider value={{ myMethod }}>
<Component />
</AppContext.Provider>
);
expect(myMethod).not.toBeCalled(); // Not Working!
});
});
I think the code explains very well what I'm trying to do, I want to cover the case where the method myMethod is not defined and therefore, the if (myMethod) should result in being false and skipped as the coverage of my code says that the if statement is covered only in the case it is true (defined).
EDIT:
I tried both not.toBeCalled() and not.toHaveBeenCalled() and they both reply with the following error:
Matcher error: received value must be a mock or spy function
Of course the error does make sense since the myMethod is of type of undefined and not a jest mock but the point is that I don't know how to achieve this.