From 970163c7b4cdb339d5a15e1e4a275ff95c7daa6a Mon Sep 17 00:00:00 2001 From: Adam Tweedie Date: Mon, 7 Mar 2022 23:28:44 +0000 Subject: [PATCH] Stopwatch: Adds tests for TimerResetButton --- .../timerResetButton/TimerResetButton.test.js | 56 +++++++++++++++++++ .../TimerResetButton.test.js.snap | 12 ++++ 2 files changed, 68 insertions(+) create mode 100644 src/components/timerResetButton/TimerResetButton.test.js create mode 100644 src/components/timerResetButton/__snapshots__/TimerResetButton.test.js.snap diff --git a/src/components/timerResetButton/TimerResetButton.test.js b/src/components/timerResetButton/TimerResetButton.test.js new file mode 100644 index 0000000..c05511b --- /dev/null +++ b/src/components/timerResetButton/TimerResetButton.test.js @@ -0,0 +1,56 @@ +import React from 'react' +import { fireEvent, render, screen } from '@testing-library/react'; +import TimerResetButton from './TimerResetButton'; + +const stubSetElapsedTime = jest.fn(); +const stubSetIsRunning = jest.fn(); +const stubUseContext = jest.fn(); + +const defaultContext = { + isRunning: false, + setElapsedTime: stubSetElapsedTime, + setIsRunning: stubSetIsRunning +} + +const renderWithContext = (context = defaultContext) => { + React.useContext = stubUseContext.mockReturnValue(context) + return render() +}; + +beforeEach(() => { + jest.useFakeTimers(); +}) + +afterEach(() => { + jest.useRealTimers(); +}); + +test('should render as expected', () => { +const component = renderWithContext(); + + expect(component.container).toMatchSnapshot(); +}); + +test('should call setElapsedTime with expected parameters on button click', () => { + renderWithContext(); + + const button = screen.getByText('Reset'); + + fireEvent.click(button) + + jest.runAllTimers(); + + expect(stubSetElapsedTime).toHaveBeenCalledWith(0); +}); + +test('should call setIsRunning with expected parameters on button click', () => { + renderWithContext(); + + const button = screen.getByText('Reset'); + + fireEvent.click(button) + + jest.runAllTimers(); + + expect(stubSetIsRunning).toHaveBeenCalledWith(false); +}); \ No newline at end of file diff --git a/src/components/timerResetButton/__snapshots__/TimerResetButton.test.js.snap b/src/components/timerResetButton/__snapshots__/TimerResetButton.test.js.snap new file mode 100644 index 0000000..4725a3e --- /dev/null +++ b/src/components/timerResetButton/__snapshots__/TimerResetButton.test.js.snap @@ -0,0 +1,12 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`should render as expected 1`] = ` +
+ +
+`;