Testing state changes inside arrow functions using Jest with a simple example

Hashini Samaraweera
2 min readMay 26, 2023

To test an arrow function in your React code base is fairly simple. Let’s look at an example below where a state change inside a function is tested.

Assume the component we are trying to test is as below. In the testFunction, we are updating the counter value in the state to 4.

import React, { Component } from 'react';

export default class TestComponent extends Component {
state = {
counter: 0
};

testFunction = () => {
this.setState(
{
counter:4
},
);
};

}

First, create your test file and import the necessary dependencies.

import React from 'react';
import { shallow } from 'enzyme';
import TestComponent from './TestComponent';

We shallow render the Batch component and obtain an instance of the component to the wrapper. The wrapper object represents the rendered component and provides various methods and properties to interact with and assert on the component. That means we can use the wrapper object to directly invoke the component’s methods.

describe ('Test'), () => {
it('should test the state change', () => {

const wrapper = shallow(<TestComponent/>);
const instance = wrapper.instance();

});

});

Then, we can then call the testFunction on the instance and test the counter value to be expected as 4.

describe ('Test'), () => {
it('should test the state change', () => {

const wrapper = shallow(<TestComponent/>);
const instance = wrapper.instance();

instance.testFunction();

expect(wrapper.state().counter).toBe(4);

});

});

And that’s it. You can build up on this and add any other necessary assertions you need for your component and check the state updates in a similar way.

--

--