You can't mock the function defined in SFC. And, we shouldn't test the implementation details of the functions. We should test the behaviour of the React Component. This is the test background and strategy for testing React Component.
So, the unit test for your sample code is:
HeaderBar.tsx:
import React from 'react';
const HeaderBar = (props: any) => {
const search = e => {
console.log(e);
};
return <div onClick={search}></div>;
};
export default HeaderBar;
HeaderBar.test.tsx:
import React from 'react';
import HeaderBar from './HeaderBar';
import { shallow } from 'enzyme';
it('mocks the search function', () => {
const logSpy = jest.spyOn(console, 'log');
const wrapper = shallow(<HeaderBar />);
const mEvent = { target: 'fake target' };
wrapper.find('div').simulate('click', mEvent);
expect(logSpy).toBeCalledWith(mEvent);
});
We can spy on console.log and test if it is to be called. If there is setState in your function, you should use wrapper.state() to test state, assert it to your expected state.
Unit test with 100% coverage:
PASS src/stackoverflow/57154476/HeaderBar.test.tsx
✓ mocks the search function (16ms)
console.log node_modules/jest-mock/build/index.js:860
{ target: 'fake target' }
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
HeaderBar.tsx | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.506s, estimated 9s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/57154476