diff --git a/jest-setup.ts b/jest-setup.ts index 7b0828b..8711eb0 100644 --- a/jest-setup.ts +++ b/jest-setup.ts @@ -1 +1,16 @@ import '@testing-library/jest-dom'; + +beforeEach(() => { + let time = 0; + jest.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { + setTimeout(() => { + time += 100; + callback(time); + }); + return time; + }); +}); + +afterEach(() => { + (window.requestAnimationFrame as jest.Mock).mockRestore(); +}); diff --git a/packages/Modal/ModalWrapper.tsx b/packages/Modal/ModalWrapper.tsx index 7adb35e..41e75c2 100644 --- a/packages/Modal/ModalWrapper.tsx +++ b/packages/Modal/ModalWrapper.tsx @@ -11,7 +11,7 @@ interface ModalWrapperProps { const ModalWrapper: FC> = ({ visible, - className = '', + className, children, ...restProps }) => { diff --git a/packages/Modal/__tests__/Modal.test.tsx b/packages/Modal/__tests__/Modal.test.tsx index f10f761..1f067f7 100644 --- a/packages/Modal/__tests__/Modal.test.tsx +++ b/packages/Modal/__tests__/Modal.test.tsx @@ -1,8 +1,10 @@ import React, { useState } from 'react'; -import { fireEvent, render } from '@testing-library/react'; +import { fireEvent, render, screen } from '@testing-library/react'; import { Button, Modal, ModalProps } from '../..'; describe('Modal', () => { + jest.useFakeTimers(); + const closeHandler = jest.fn(); const Component = (props: ModalProps) => { @@ -88,14 +90,14 @@ describe('Modal', () => { test('should open modal and close modal when click target', () => { const { getByTestId } = render(); fireEvent.click(getByTestId('openModal')); - setTimeout(() => { - expect('This is a modal.').toBeInTheDocument(); - }, 50); + jest.runAllTimers(); + expect(screen.getByText('This is a modal.')).toBeInTheDocument(); fireEvent.click(document.querySelector('.raw-modal-container')); - setTimeout(() => { - expect('This is a modal.').not.toBeInTheDocument(); - expect(closeHandler).toHaveBeenCalledTimes(1); - }, 350); + jest.runAllTimers(); + expect( + document.querySelector('.raw-modal-container') + ).not.toBeInTheDocument(); + expect(closeHandler).toHaveBeenCalledTimes(1); }); test('should not close modal when disabled overlay clicked', () => { @@ -104,4 +106,14 @@ describe('Modal', () => { fireEvent.click(document.querySelector('.raw-modal-container')); expect(closeHandler).toHaveBeenCalledTimes(0); }); + + test('should not propagate the click event', () => { + const { getByTestId } = render(); + fireEvent.click(getByTestId('openModal')); + const modalWrapper = screen.getByTestId('modalWrapper') as Element; + expect(screen.getByText('This is a modal.')).toBeInTheDocument(); + fireEvent.click(modalWrapper); + expect(screen.getByText('This is a modal.')).toBeInTheDocument(); + expect(closeHandler).toHaveBeenCalledTimes(0); + }); });