Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jest fake timer 사용시 userEvent.click 미동작 이슈 #13

Open
j03y14 opened this issue Aug 31, 2023 · 0 comments
Open

jest fake timer 사용시 userEvent.click 미동작 이슈 #13

j03y14 opened this issue Aug 31, 2023 · 0 comments
Assignees

Comments

@j03y14
Copy link
Contributor

j03y14 commented Aug 31, 2023

문제 상황

beforeEach(() => {
    timeLimitMs = 10000;
    jest.useFakeTimers();

    render(
      <Timer
        timeLimit={timeLimitMs}
        initGame={initGame}
      />,
    );
  });

...

test('타이머 테스트', async () => {
    const startButton = screen.getByRole('button', { name: '시작' });

    await userEvent.click(startButton);

    act(() => {
      jest.advanceTimersByTime(1000);
    });

    const remainTimeView = screen.getByRole('remainTimeView');
    expect(remainTimeView).toHaveTextContent('9 초');
  });

이렇게 코드가 되어있을 때 테스트가 타임아웃 안에 안 끝나는 현상 발생.
콘솔을 찍어보면서 어디가 문제인지를 확인해봤더니 await userEvent.click()을 했을 때 클릭 이벤트 핸들러가 호출이 되지 않고 있었다.

관련이슈를 보니 userEvent 내부적으로 delay 옵션만큼 setTimeout을 이용해서 기다리고 있었다. 그런데 fake timer를 사용했기 때문에 userEvent의 setTimeout이 실행되지 않아서 이벤트가 호출되지 않은 것이다.

해결

1.

erEvent에서 옵션 중에 delay: null로 설정하면 setTimeout을 호출하지 않기 때문에 의도한 동작대로 테스트 수행이 가능했다.

const user = userEvent.setup({ delay: null });

2.

https://testing-library.com/docs/user-event/options/#advancetimers

fake timer를 사용할 때 delay를 실행시켜주기 위해서 advanceTimers 옵션을 줄 수 있다.

const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });

참조

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants