TommyD
TommyD

Reputation: 1043

React Testing Library - mocking a function

I am trying to test a function gets called

import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import MyForm from './MyForm';

afterEach(cleanup);
const testFunction = jest.fn();
test('my form', () => {
  const { getByTestId } = render(<MyForm />);
  const myButton = getByTestId('submit-button');
  expect(myButton.tagName).toBe('BUTTON');
  fireEvent.click(myButton)
  expect(testFunction).toHaveBeenCalledTimes(1)
});

The problem I am having is it does not seem to bind to the mock function but it does call the function in the component.

import React from 'react';

export default function myForm() {
  function testFunction() {
    console.log('hello from inside');
  }
  return (
    <div>
      <form onSubmit={testFunction}>
        <input type="text" />
        <button type="submit" data-testid="submit-button">submit</button>
      </form>
    </div>
  );
}

How do I get the mock function the be called rather than the 'real' function.

expect(jest.fn()).toHaveBeenCalledTimes(1)
    
    Expected mock function to have been called one time, but it was called zero times.

Upvotes: 5

Views: 14763

Answers (1)

Emmanuel Ponnudurai
Emmanuel Ponnudurai

Reputation: 1084

You cannot call the internal functions of myForm. You can test the behavior and the final tangible output but not private functionality of a component.

And it does make sense as well. A unit test should concern itself with the outcome and not if a specific function internal to that component is called.

Yes, you can always test the behavior. For instance, you can test that console.log is called cos that is visible to the outside world in terms of a tangible thing.

Similarly, if testFuntion does something else which you can assert, you can test that as well.

Another option is to pull testFunction out and export it so it can be used anywhere. Then you write a unit test for just testFunction's functionality may be, but not within the context of the components unit test

Upvotes: 5

Related Questions