5

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.
2
  • Does your testFunction have to be (hidden) inside the myForm component? If it were a prop, you could pass it in your test and then the mock function would get called. Commented Sep 3, 2021 at 12:50
  • I have seen that done - in almost every example. I would be modifying my code to fit the test. I could but it seems wrong to me. Commented Sep 3, 2021 at 12:56

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

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.