walee
walee

Reputation: 615

How to test non-export function in Reactjs

I have watched many tutorial videos on testing, but usually those tests test passed props to component or uses data-testid="". Is there a way to test non-exported functions? I read about rewire module which does this but problem with that is that Jest will not consider functions called from rewire in coverage reports.

// Random.js
import React from 'react'

export function sayHi() {
  return '👋';
}

function ListBox() {

  function saySecret() {
    return '🤫';
  }
    
  return (
    <div>ListBox</div>
  )
}

export default ListBox

First one which has export would be :

 // Random.test.js
 import { sayHi } from './Random.js';

 describe('sayHi', () => {
   it('returns wave emoji', () => {
     expect(sayHi()).toBe('👋');
   });
 });

How should I test saySecret?

Upvotes: 2

Views: 1653

Answers (1)

Ben Clayton
Ben Clayton

Reputation: 82267

The short answer is you can't test those functions in isolation to the ListBox component itself.

The better answer is that you shouldn't. At least the react-testing-library philosophy is:

you want your tests to avoid including implementation details of your components

https://testing-library.com/docs/react-testing-library/intro/

.. and functions that exist only inside a component would very much count as implementation details.

If you need to increase your code coverage, then use react-testing-library to 'use' the component in such a way that the functions are called.

If the functions are reusable bits of code, then move them outside the component, and export them. Then you can test them in the usual way.

Upvotes: 3

Related Questions