Gareema
Gareema

Reputation: 31

How to write unit tests for a function call in a div in enzyme and jest?

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?

Upvotes: 0

Views: 791

Answers (1)

Kiran Parajuli
Kiran Parajuli

Reputation: 1045

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();
});

Upvotes: 0

Related Questions