Skip to content

Instantly share code, notes, and snippets.

@jgcmarins
Last active May 15, 2019 20:56
Show Gist options
  • Save jgcmarins/c564d5a111a7c078000d1abe4b9203fb to your computer and use it in GitHub Desktop.
Save jgcmarins/c564d5a111a7c078000d1abe4b9203fb to your computer and use it in GitHub Desktop.
Testing functions only called by useEffect
import React from 'react';
import { mount } from 'enzyme';
import formEventEmitter from '../formEventEmitter';
import MyFunctionComponent from '../MyFunctionComponent';
jest.mock('../formEventEmitter');
it('should check if preventCancel is being called', () => {
const dialog = { confirm: jest.fn() };
const preventCancel = jest.fn();
const cb = jest.fn();
// here is where the magic ✨ happens, thanks to @gabrielgene
formEventEmitter.on.mockImplementation((_, handleCancelEvent) => handleCancelEvent(preventCancel, cb));
mount(<MyFunctionComponent keySignal={'a'} isDirty={true} dialog={dialog} />).mount();
expect(preventCancel).toHaveBeenCalledTimes(1);
expect(dialog.confirm).toHaveBeenCalledTimes(1);
});
import React, { useEffect } from 'react';
import formEventEmitter from './formEventEmitter';
import { withConfirmDialog, ConfirmDialogProps } from './withConfirmDialog';
type Props = {
keySignal: string;
isDirty?: boolean | null;
} & ConfirmDialogProps;
export const MyFunctionComponent = ({ keySignal, isDirty = false, dialog }: Props) => {
const handleCancelEvent = (preventCancel: () => void, onConfirm: () => void) => {
if(isDirty) {
preventCancel(); // we wanna check if this function will be called
dialog.comfirm({
title: 'Title',
description: 'Description',
onConfirm,
});
}
}
}
useEffect(() => {
formEventEmitter.on(keySignal, handleCancelFormEvent);
return () => {
formEventEmitter.removeListener(keySignal, handleCancelFormEvent);
}
}, []);
return null;
};
export default withConfirmDialog(MyFunctionComponent);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment