Skip to content

Commit

Permalink
Stopwatch: Adds tests for TimerToggleButton
Browse files Browse the repository at this point in the history
  • Loading branch information
atweedie committed Mar 7, 2022
1 parent 970163c commit 3eab277
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/components/timerToggleButton/TimerToggleButton.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import React from 'react'
import { fireEvent, render, screen } from '@testing-library/react';
import TimerToggleButton from './TimerToggleButton';

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(<TimerToggleButton/>)
};

beforeEach(() => {
jest.useFakeTimers();
})

afterEach(() => {
jest.useRealTimers();
});

test('should render as expected when isRunning is set to false', () => {
const component = renderWithContext();

expect(component.container).toMatchSnapshot();
});

test('should render as expected when isRunning is set to true', () => {
const givenContext = {
...defaultContext,
isRunning: true
}

const component = renderWithContext(givenContext);

expect(component.container).toMatchSnapshot();
});

test('should call setIsRunning with true on button click when isRunning is false', () => {
renderWithContext();

const button = screen.getByText('Start');

fireEvent.click(button)

jest.runAllTimers();

expect(stubSetIsRunning).toHaveBeenCalledWith(true);
});

test('should call setIsRunning with false on button click when isRunning is true', () => {
const givenContext = {
...defaultContext,
isRunning: true
}

renderWithContext(givenContext);

const button = screen.getByText('Stop');

fireEvent.click(button)

jest.runAllTimers();

expect(stubSetIsRunning).toHaveBeenCalledWith(false);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`should render as expected when isRunning is set to false 1`] = `
<div>
<button
class="button"
id="stopwatch-start-stop"
>
Start
</button>
</div>
`;

exports[`should render as expected when isRunning is set to true 1`] = `
<div>
<button
class="button"
id="stopwatch-start-stop"
>
Stop
</button>
</div>
`;

0 comments on commit 3eab277

Please sign in to comment.