Kamrul Khan
Kamrul Khan

Reputation: 3360

React: How mock functions and test component rendering with jest:

Im very new to react/jest. Im trying to test a very simple react component that gets data from the server and renders the response. My component looks like the below:

export default class myComponent extends Component {
    constructor(props) {
        super(props);
    }

     async componentDidMount() {
        try {
            let response = await axios.get(`server/url/endpoint`);
            this._processSuccess(response.data);
        } catch(e) {
            this._processFail(e);
        }
    }

    _processSuccess(response) {
        this.setState({pageTitle: response.data.title, text: response.data.text});
    }

    render() {
        return (
            <div className="title">{this.state.pageTitle}</div>
        );
    }
}

Now I want to test this class. While I test:

  1. I want to make sure componentDidMount() was not called
  2. I want to pass test data to _processSuccess
  3. Finally check the if the rendered output contains a div with class title that has the inner text same as what I supplied as response.data/pageTitle

I tried something like the below:

import React from 'react'
import MyComponent from './MyComponent'
import renderer from 'react-test-renderer'
import { shallow, mount } from 'enzyme'

describe('MyComponent', () => {
    it('should display proper title', () => {
        const c = shallow(<MyComponent />);
        c._processSuccess(
            {data:{pageTitle:'siteName', test:'text'}}
        );
        // couldn't go further as Im getting error from the above line
    });
});

But, Im getting MyComponent._processSuccess is not a function error. What would be the proper way to do that.

Upvotes: 2

Views: 2109

Answers (1)

lorenzo-s
lorenzo-s

Reputation: 17010

shallow() returns an Enzyme wrapper with some utils method to test the rendered component. It does not return the component instance. That's why you get the error when calling c._processSucces(). To access the component you can use the .instance() method on the wrapper, so the following should work:

    const c = shallow(<MyComponent />);
    c.instance()._processSuccess(
        {data:{pageTitle:'siteName', test:'text'}}
    );

In order to avoid that component's componentDidMount() get called, you can try settings disableLifecycleMethods on the shallow renderer, but I'm not sure about that because here Enzyme's documentation is not 100% clear:

    const c = shallow(<MyComponent />, {
        disableLifecycleMethods: true
    });

Finally, you can check if the output contains the expected <div>, using Enzyme's contains() and one of Jest assertion methods:

    expect(c.contains(<div className="title" />)).toBe(true);

Upvotes: 3

Related Questions