Testing with jest/vitest #123
-
This is not really a bug but rather a stumping behaviour. function renderImageEditor({ open = true, useEdited = false }: { open?: boolean, useEdited?: boolean } = {}) {
const mockOnClose = vi.fn();
const mockOnEdit = vi.fn();
const mockOriginalImage = 'original';
const mockEditedImage = 'edited';
const getters = render(
<ImageEditor
open={open}
originalImage={mockOriginalImage}
editedImage={useEdited ? mockEditedImage : undefined}
onClose={mockOnClose}
onEdit={mockOnEdit}
/>,
);
return {
...getters, mockOnEdit, mockOnClose, mockOriginalImage, mockEditedImage,
};
}
it('should submit new image when saving after editing', () => {
const {
getByTestId, mockOnEdit, mockEditedImage, mockOriginalImage,
} = renderImageEditor({ useEdited: true });
const canvas = document.getElementById(imageEditorTestIds.canvas)!;
fireEvent.mouseDown(canvas);
fireEvent.mouseMove(canvas);
fireEvent.mouseUp(canvas);
const button = getByTestId(imageEditorTestIds.submit);
fireEvent.click(button);
expect(mockOnEdit).toHaveBeenCalled();
expect(mockOnEdit).not.toHaveBeenCalledWith(mockEditedImage);
expect(mockOnEdit).not.toHaveBeenCalledWith(mockOriginalImage);
});
}); I'm using For brevity, here is my minimal component: function Component = ({onEdit, originalImage, editedImage}) => {
const [isEdited, setIsEdited] = useState<boolean>(false);
const canvasRef = useRef<ReactSketchCanvasRef>(null);
const onSubmit = async () => {
if (isEdited) {
const data = await canvasRef.current?.exportImage('jpeg');
onEdit(data || originalImage);
onClose();
}
};
return <div data-testid={testIds.wrapper}>
<ReactSketchCanvas
id={testIds.canvas}
ref={canvasRef}
backgroundImage={editedImage || originalImage}
className='w-full h-full'
strokeWidth={4}
strokeColor='red'
exportWithBackgroundImage
onStroke={() => setIsEdited(true)}
/>
</div> If |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The |
Beta Was this translation helpful? Give feedback.
The
jsdom
in vitest or Jest does not support pointer events, making it impossible to unit test this functionality. Instead, you need to utilize a component test using playwright or Cypress.