1

I am testing a component following the Container/Presentational pattern. What I need in order to have my coverage at 100% is to test the handleChange() function in which I have a setState(). The thing is that I'm just testing the Container component and the function is called in Presentational one.

Container Component:

import React, { Component } from 'react'
import DataStructureFormView from './DataStructureFormView'

export default class DataStructureForm extends Component {
    state = {}

    handleChange = name => event => {
        this.setState({
            [name]: event.target.value
        })
    }

    render() {
        return (
            <DataStructureFormView
               handleChange={this.handleChange}
               form={this.state}
            />
        )
    }
}

As you can see, the DataStructureForm is the Container component and DataStructureFormView is the Presentational one.

Test file:

import React from 'react'
import { shallow, mount } from 'enzyme'

describe('DataStructureForm', () => {
    it('should call the handleChange() function and change the state', () => {
        const component = mount(<DataStructureForm />)

        const handleChange = jest.spyOn(component.instance(), 'handleChange')

        component.instance().handleChange()

        expect(handleChange).toBeCalled()
     }
}

This is one of the multiple approaches that I have done, but it is not testing the setState() inside the handleChange() method.

What else I can do?

1 Answer 1

1

The most straightforward solution is to check if state changed accordingly:

const component = shallow(<DataStructureForm />)
const value = 'someValue';
component.instance().handleChange('someName')({target: { value }});
expect(component.state('someName')).toEqual(value)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Alex, that is the solution. The problem was I didn't how to call the handleChange() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.