besrabasant
besrabasant

Reputation: 2850

mock function that is called inside react component render function

First of all I want to let know that I am new to testing with react and want to verify if I am writing the right tests.

I have a React Component something like this -

import React, { Component } from "react";

class DemoComponent extends Component
{
    returnSomething()
    {
       return "something";
    }

    render(){
        return(
          <div>{ this.returnSomething() }</div>
        );
    }
}

and I am writing to test to verify method calls something like this -

import React from "react";
import { shallow } from "enzyme";
import DemoComponent from "./DemoComponent.js";

const component = shallow(<DemoComponent/>); 

test('"returnSomething" method is called when the component is rendered', () => {
    component.instance().returnSomething= jest.fn();
    component.update();
    component.instance().render();
    expect(component.instance().returnSomething).toHaveBeenCalled();
});

The test runs ok but I want to know if the test I have written is the correct way.

Upvotes: 1

Views: 2180

Answers (1)

Patrick Finnigan
Patrick Finnigan

Reputation: 1967

You were able to write a test here that passes, so I don't see a problem.

Just testing that some method on the component was called doesn't really tell you anything about the result of render() - how the component renders. As Andreas points out, testing a snapshot of the render() is probably better (assuming you're using Jest) - that way you're testing the actual render results and not just checking whether some method got called during render. Alternatively you could use something like .matchesElement() or check for individual properties to create a stronger test.

Upvotes: 2

Related Questions