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.
testFunctionhave 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.