jeudi 17 août 2017

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 http://ift.tt/2weS0nd

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.

Aucun commentaire:

Enregistrer un commentaire