0

I have a function call in my react component. I need to write the unit tests for it. Here is my function definition:

const renderError = () =>{
    const {isError, errorMessage, errorFromWhere} = error;
    if(isError && errorFromWhere === "fromDraft"){
        return (
            <div className="action-button-error">
                <Notification type={"warning"} text={errorMessage} />
            </div>
        );
    }
    return null;
};

Here is the return statement:

return (
    <div className="action-buttons-wrapper">
            
            <div className="right-section">
                {
                    renderError()
                }
</div>
</div>);

I need to test the renderError() method. I tried it by using shallow rendering and then tried to access the method by wrapper.instance(). But this is returning null. Here is the UT that I tried:

it("testing the render error function", ()=>{
        const wrapper=shallow(<ActionButtons {...defaultProps}/>);
        const spy=jest.spyOn(wrapper.instance(), "renderError");
        expect(spy).toHaveBeenCalled();
console.log(wrapper.instance());
});

This console.log prints null. I am not able to figure how to check this method. Anyone who can guide me here?

Gareema
  • 21
  • 1
  • 5

1 Answers1

0

you've to spy on the targetted function before initializing it on the wrapper var. try this:

it("testing the render error function", () => {
    // register the spy first
    const spy = jest.spyOn(ActionButtons.prototype, "renderError")
    // then mount it as the `wrapper`
    const wrapper=shallow(<ActionButtons {...defaultProps}/>);
    expect(spy).toHaveBeenCalled();
});
Kiran Parajuli
  • 820
  • 6
  • 14
  • This gives me an error: Cannot spy the renderError property because it is not a function; undefined given instead. – Gareema Jul 11 '22 at 06:28