How to test a function inside a stateless component using JEST in ReactJS?

When we want to test a method inside a stateless component or functional component, we can consider using user interaction events such as click, change or focus, etc.

The advice of Dave Thomas and Andy Hunt in their book Pragmatic Unit Testing:

In general, you don’t want to break any encapsulation for the sake of testing (or as Mom used to say, “don’t expose your privates!”). Most of the time, you should be able to test a class by exercising its public methods.

We should not test private items, it is considered bad practice to test internal implementation. A private method is an implementation detail that should be hidden to the users of the class. Testing private methods break encapsulation.

Many developers have different opinions about it. In the case of a stateless component, if we want to test a function (private) we need to add user interaction with the component. Consider the following component:

function App() {

const setPageTitle = () => {
    document.title = 'React Application';
};

return (
    <div>
        <div className="set-title" onClick={setPageTitle}>Set title</div>
    </div>
);

}

The test case:

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

describe('Application home page test cases', () => {
  it('Test private method', () => {
    const wrapper = shallow(<App/>);
    wrapper.find('div.set-title').simulate('click');
    expect(document.title).toBe('React Application');
  });
});