How to use jest.spyOn with React function component using Typescript
Your validateBeforeSave
function is declared within SomeComponent
making it a closed/private scope function not accessible outside. You can pass that function as a prop and you can then create spy and pass it as a prop value in your test and test for if the prop function passed (spy) was called or not
So you would modify your function somewhat like this:
// some validator function
function validateBeforeSave(){
...
}
// Some function Component
const SomeComponent = (props: IMyComponentProps) => {
const { classes, validateBeforeSave } = props;
// Component has state
const [count, setCount] = useState(0);
function handleClick() {
validateBeforeSave();
.
.
.
}
return (
<div>
<Button>
className="saveBtn"
onClick={handleClick}
</Button>
</div>
);
};
And In your Unit test, something like this:
// Unit test
describe('SomeComponent' () => {
it('validates model on button click', () => {
const validateSpy = jest.fn();
const wrapper = mount(
<MuiThemeProvider theme={theme}>
<SomeComponent validateSpy={validateSpy}/>
</MuiThemeProvider>,
);
const instance = wrapper.instance();
wrapper
.find('.saveBtn')
.at(0)
.simulate('click');
expect(validateSpy).toHaveBeenCalledTimes(1);
});
}