12 Commits

Author SHA1 Message Date
Steve Kinney
5b93f0ac4b Reapply "Accident counter"
This reverts commit 9d5615cb9d.
2024-10-08 17:05:00 -06:00
Steve Kinney
9d5615cb9d Revert "Accident counter"
This reverts commit 9cb1a0c739.
2024-10-02 16:27:23 -05:00
Steve Kinney
a9e36ee3c8 Play with time 2024-10-02 16:26:35 -05:00
Steve Kinney
8fb10ac976 Update game.test.js 2024-10-02 15:41:32 -05:00
Steve Kinney
25f1a63b96 Getting the button working 2024-10-02 15:38:54 -05:00
Steve Kinney
2552cb26d5 Explorations with mocking 2024-10-02 15:38:38 -05:00
Steve Kinney
9cb1a0c739 Accident counter 2024-10-02 15:38:16 -05:00
Steve Kinney
579a55a4ae Update alert-button.test.jsx 2024-10-02 15:38:02 -05:00
Steve Kinney
a3b3d154c3 Update character.test.ts 2024-10-02 12:54:12 -05:00
Steve Kinney
058fe1fdc8 Update person.test.js 2024-10-02 12:53:23 -05:00
Steve Kinney
9e2cfcee70 Finish testing mathematics 2024-10-02 12:26:17 -05:00
Steve Kinney
672d11c88b Implement addition 2024-10-02 10:28:38 -05:00
16 changed files with 333 additions and 77 deletions

View File

@@ -1,16 +0,0 @@
## Testing Fundamentals Course
This is a companion repository for the [Testing Fundamentals](https://frontendmasters.com/courses/testing/) course on Frontend Masters.
[![Frontend Masters](https://static.frontendmasters.com/assets/brand/logos/full.png)](https://frontendmasters.com/courses/testing/)
## Setup Instructions
> We recommend using Node.js version 20+ for this course
Clone this repository and install the dependencies:
```bash
git clone https://github.com/stevekinney/introduction-to-testing.git
cd introduction-to-testing
npm install
```

View File

@@ -1,34 +1,82 @@
import { render, screen } from '@testing-library/react'; import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { Counter } from './counter'; import { Counter } from './counter';
import '@testing-library/jest-dom/vitest'; import '@testing-library/jest-dom/vitest';
describe.todo('Counter ', () => { describe('Counter ', () => {
beforeEach(() => { it('renders with an initial count of 0', () => {
render(<Counter />); render(<Counter />);
const counter = screen.getByTestId('counter-count');
expect(counter).toHaveTextContent('0');
}); });
it('renders with an initial count of 0'); it('disables the "Decrement" and "Reset" buttons when the count is 0', () => {
render(<Counter />);
const decrementButton = screen.getByRole('button', { name: /decrement/i });
const resetButton = screen.getByRole('button', { name: /reset/i });
it('disables the "Decrement" and "Reset" buttons when the count is 0'); expect(decrementButton).toBeDisabled();
expect(resetButton).toBeDisabled();
});
it.todo('displays "days" when the count is 0', () => {}); it('displays "days" when the count is 0', () => {
render(<Counter />);
const unit = screen.getByTestId('counter-unit');
expect(unit).toHaveTextContent('days');
});
it.todo( it('increments the count when the "Increment" button is clicked', async () => {
'increments the count when the "Increment" button is clicked', render(<Counter />);
async () => {}, const incrementButton = screen.getByRole('button', { name: /increment/i });
); const counter = screen.getByTestId('counter-count');
it.todo('displays "day" when the count is 1', async () => {}); await act(async () => {
await userEvent.click(incrementButton);
});
it.todo( expect(counter).toHaveTextContent('1');
'decrements the count when the "Decrement" button is clicked', });
async () => {},
);
it.todo('does not allow decrementing below 0', async () => {}); it('displays "day" when the count is 1', async () => {
render(<Counter />);
const incrementButton = screen.getByRole('button', { name: /increment/i });
const unit = screen.getByTestId('counter-unit');
await act(async () => {
await userEvent.click(incrementButton);
});
expect(unit).toHaveTextContent('day');
});
it('decrements the count when the "Decrement" button is clicked', async () => {
render(<Counter initialCount={1} />);
const decrementButton = screen.getByRole('button', { name: /decrement/i });
const count = screen.getByTestId('counter-count');
expect(decrementButton).not.toBeDisabled();
await act(async () => {
await userEvent.click(decrementButton);
});
expect(count).toHaveTextContent('0');
expect(decrementButton).toBeDisabled();
});
it('does not allow decrementing below 0', async () => {
render(<Counter />);
const decrementButton = screen.getByRole('button', { name: /decrement/i });
const count = screen.getByTestId('counter-count');
await act(async () => {
await userEvent.click(decrementButton);
});
expect(count).toHaveTextContent('0');
});
it.todo( it.todo(
'resets the count when the "Reset" button is clicked', 'resets the count when the "Reset" button is clicked',
@@ -40,5 +88,14 @@ describe.todo('Counter ', () => {
() => {}, () => {},
); );
it.todo('updates the document title based on the count', async () => {}); it('updates the document title based on the count', async () => {
const { getByRole } = render(<Counter />);
const incrementButton = getByRole('button', { name: /increment/i });
await act(async () => {
await userEvent.click(incrementButton);
});
expect(document.title).toEqual(expect.stringContaining('1 day'));
});
}); });

View File

@@ -2,8 +2,8 @@ import React from 'react';
import { useReducer, useEffect } from 'react'; import { useReducer, useEffect } from 'react';
import { reducer } from './reducer'; import { reducer } from './reducer';
export const Counter = () => { export const Counter = ({ initialCount = 0 }) => {
const [state, dispatch] = useReducer(reducer, { count: 0 }); const [state, dispatch] = useReducer(reducer, { count: initialCount });
const unit = state.count === 1 ? 'day' : 'days'; const unit = state.count === 1 ? 'day' : 'days';
useEffect(() => { useEffect(() => {

View File

@@ -1,7 +1,28 @@
export const add = () => {}; export const add = (a, b) => {
if (typeof a === 'string') a = Number(a);
if (typeof b === 'string') b = Number(b);
export const subtract = () => {}; if (isNaN(a)) throw new Error('The first argument is not a number');
if (isNaN(b)) throw new Error('The second argument is not a number');
export const multiply = () => {}; return a + b;
};
export const divide = () => {}; export const subtract = (a = 0, b = 0) => {
if (Array.isArray(a)) {
a = a.reduce((a, b) => {
return a - b;
});
}
return a - b;
};
export const multiply = (a, b) => {
return a * b;
};
export const divide = (a, b) => {
if (b === 0) return null;
return a / b;
};

View File

@@ -1,9 +1,72 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { add, subtract, multiply, divide } from './arithmetic.js';
describe.todo('add', () => {}); describe('add', () => {
it('should add two positive numbers', () => {
expect(add(2, 2)).toBe(4);
});
describe.todo('subtract', () => {}); it('should add two negative numbers', () => {
expect(add(-2, -2)).toBe(-4);
});
describe.todo('multiply', () => {}); it('should parse strings into numbers', () => {
expect(add('1', '1')).toBe(2);
});
describe.todo('divide', () => {}); it('should get real angry if you give it a first argument that cannot be parsed into a number', () => {
expect(() => add('potato', 2)).toThrow('not a number');
});
it('should get real angry if you give it a second argument that cannot be parsed into a number', () => {
expect(() => add(2, 'potato')).toThrow('not a number');
});
it('should throw if the first argument is not a number', () => {
expect(() => add(NaN, 2)).toThrow('not a number');
});
it('should handle floating point math as best it can', () => {
expect(add(1.0000001, 2.0000004)).toBeCloseTo(3.0, 1);
});
});
describe('subtract', () => {
it('should subtract one number from the other', () => {
expect(subtract(4, 2)).toBe(2);
});
it('should accept and subtract all of the numbers', () => {
expect(subtract([10, 5], 2)).toBe(3);
});
it('should default undefined values to 0', () => {
expect(subtract(3)).toBe(3);
expect(subtract(undefined, 3)).toBe(-3);
});
it('should default to zero if either argument is null', () => {
expect(subtract(3, null)).toBe(3);
expect(subtract(null, 3)).toBe(-3);
});
});
describe('multiply', () => {
it('should multiply two numbers', () => {
expect(multiply(3, 2)).toBe(6);
});
});
describe('divide', () => {
it('should divide two numbers', () => {
expect(divide(10, 2)).toBe(5);
});
it('should return null if dividing by zero', () => {
expect(divide(10, 0)).toBeNull();
});
it('should return zero if dividing by Infinity', () => {
expect(divide(10, Infinity)).toBe(0);
});
});

View File

@@ -2,21 +2,21 @@ import { Person } from './person.js';
import { rollDice } from './roll-dice.js'; import { rollDice } from './roll-dice.js';
export class Character extends Person { export class Character extends Person {
constructor(firstName, lastName, role) { constructor(firstName, lastName, role, level = 1, roll = rollDice) {
super(firstName, lastName); super(firstName, lastName);
this.role = role; this.role = role;
this.level = 1; this.level = level;
this.createdAt = new Date(); this.createdAt = new Date();
this.lastModified = this.createdAt; this.lastModified = this.createdAt;
this.strength = rollDice(4, 6); this.strength = roll(4, 6);
this.dexterity = rollDice(4, 6); this.dexterity = roll(4, 6);
this.intelligence = rollDice(4, 6); this.intelligence = roll(4, 6);
this.wisdom = rollDice(4, 6); this.wisdom = roll(4, 6);
this.charisma = rollDice(4, 6); this.charisma = roll(4, 6);
this.constitution = rollDice(4, 6); this.constitution = roll(4, 6);
} }
levelUp() { levelUp() {

View File

@@ -1,14 +1,60 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { Character } from './character.js'; import { Character } from './character.js';
import { Person } from './person.js'; import { Person } from './person.js';
const firstName = 'Ada';
const lastName = 'Lovelace';
const role = 'Computer Scienst';
describe('Character', () => { describe('Character', () => {
it.todo( let character;
'should create a character with a first name, last name, and role',
() => {},
);
it.todo('should allow you to increase the level', () => {}); beforeEach(() => {
character = new Character(firstName, lastName, role, 1);
it.todo('should update the last modified date when leveling up', () => {}); });
it.skip('should create a character with a first name, last name, and role', () => {
expect(character).toEqual({
firstName,
lastName,
role,
strength: 12,
wisdom: 12,
dexterity: 12,
intelligence: 12,
constitution: 12,
charisma: 12,
level: 1,
lastModified: expect.any(Date),
createdAt: expect.any(Date),
id: expect.stringContaining('person-'),
});
});
it('should allow you to increase the level', () => {
const initialLevel = character.level;
character.levelUp();
expect(character.level).toBeGreaterThan(initialLevel);
});
it('should update the last modified date when leveling up', () => {
const initialLastModified = character.lastModified;
character.levelUp();
expect(character.lastModified).not.toBe(initialLastModified);
});
it.only('should roll four six-sided die', () => {
const rollDiceMock = vi.fn(() => 15);
const character = new Character(firstName, lastName, role, 1, rollDiceMock);
expect(character.strength).toBe(15);
expect(rollDiceMock).toHaveBeenCalledWith(4, 6);
expect(rollDiceMock).toHaveBeenCalledTimes(6);
console.log(rollDiceMock.mock.calls);
});
}); });

View File

@@ -2,11 +2,12 @@ import { describe, it, expect } from 'vitest';
import { Person } from './person.js'; import { Person } from './person.js';
// Remove the `todo` from the `describe` to run the tests. // Remove the `todo` from the `describe` to run the tests.
describe.todo('Person', () => { describe('Person', () => {
// This test will fail. Why? // This test will fail. Why?
it('should create a person with a first name and last name', () => { it('should create a person with a first name and last name', () => {
const person = new Person('Grace', 'Hopper'); const person = new Person('Grace', 'Hopper');
expect(person).toEqual({ expect(person).toEqual({
id: expect.stringContaining('person-'),
firstName: 'Grace', firstName: 'Grace',
lastName: 'Hopper', lastName: 'Hopper',
}); });

View File

@@ -1,7 +1,10 @@
import { useState } from 'react'; import { useState } from 'react';
export const AlertButton = ({}) => { export const AlertButton = ({
const [message, setMessage] = useState('Alert!'); onSubmit = () => {},
defaultMessage = 'Alert!',
}) => {
const [message, setMessage] = useState(defaultMessage);
return ( return (
<div> <div>
@@ -14,7 +17,7 @@ export const AlertButton = ({}) => {
/> />
</label> </label>
<button onClick={() => alert(message)}>Trigger Alert</button> <button onClick={() => onSubmit(message)}>Trigger Alert</button>
</div> </div>
); );
}; };

View File

@@ -3,12 +3,28 @@ import userEvent from '@testing-library/user-event';
import { AlertButton } from './alert-button'; import { AlertButton } from './alert-button';
describe.todo('AlertButton', () => { describe('AlertButton', () => {
beforeEach(() => {}); beforeEach(() => {});
afterEach(() => {}); afterEach(() => {});
it('should render an alert button', async () => {}); it('should render an alert button', async () => {});
it('should trigger an alert', async () => {}); it.only('should trigger an alert', async () => {
const handleSubmit = vi.fn();
render(<AlertButton onSubmit={handleSubmit} message="Default Message" />);
const input = screen.getByLabelText('Message');
const button = screen.getByRole('button', { name: /trigger alert/i });
await act(async () => {
await userEvent.clear(input);
await userEvent.type(input, 'Hello');
await userEvent.click(button);
});
expect(handleSubmit).toHaveBeenCalled();
expect(handleSubmit).toHaveBeenCalledWith('Hello');
});
}); });

View File

@@ -1,9 +1,26 @@
import { screen, fireEvent } from '@testing-library/dom';
import userEvent from '@testing-library/user-event';
import { createButton } from './button.js'; import { createButton } from './button.js';
describe.todo('createButton', () => { describe('createButton', () => {
it('should create a button element', () => {}); beforeEach(() => {
document.innerHTML = '';
it('should have the text "Click Me"', () => {}); });
it('should change the text to "Clicked!" when clicked', async () => {}); it.skip('should create a button element', () => {
document.body.appendChild(createButton());
const button = screen.getByRole('button', { name: 'Click Me' });
expect(button).toBeInTheDocument();
});
it('should change the text to "Clicked!" when clicked', async () => {
document.body.appendChild(createButton());
const button = screen.getByRole('button', { name: 'Click Me' });
await userEvent.click(button);
expect(button.textContent).toBe('Clicked!');
});
}); });

View File

@@ -9,7 +9,7 @@ describe('Game', () => {
}); });
it('should have a secret number', () => { it('should have a secret number', () => {
// Thisn't really a useful test. // This isn't really a useful test.
// Do I *really* care about the type of the secret number? // Do I *really* care about the type of the secret number?
// Do I *really* care about the name of a "private" property? // Do I *really* care about the name of a "private" property?
const game = new Game(); const game = new Game();

View File

@@ -6,11 +6,14 @@ import { sendToServer } from './send-to-server';
* Log a message to the console in development mode or send it to the server in production mode. * Log a message to the console in development mode or send it to the server in production mode.
* @param {string} message * @param {string} message
*/ */
export function log(message) { export function log(
if (import.meta.env.MODE !== 'production') { message,
{ productionCallback = () => {}, mode = import.meta.env.MODE } = {},
) {
if (mode !== 'production') {
console.log(message); console.log(message);
} else { } else {
sendToServer('info', message); productionCallback('info', message);
} }
} }

View File

@@ -1,4 +1,33 @@
import { expect, it, vi, beforeEach, afterEach, describe } from 'vitest'; import { expect, it, vi, beforeEach, afterEach, describe } from 'vitest';
import { log } from './log'; import { log } from './log';
describe.todo('logger', () => {}); describe('logger', () => {
describe('development', () => {
it('logs to the console in development mode', () => {
const logSpy = vi.fn();
log('Hello World');
expect(logSpy).toHaveBeenCalledWith('Hello World');
});
});
describe('production', () => {
beforeEach(() => {
vi.stubEnv('MODE', 'production');
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should not call console.log in production', () => {
const logSpy = vi.spyOn(console, 'log');
log('Hello World', { mode: 'production', productionCallback: logSpy });
expect(logSpy).not.toHaveBeenCalled();
expect(sendToServer).toHaveBeenCalled();
});
});
});

View File

@@ -4,5 +4,6 @@
* @param {string} message * @param {string} message
*/ */
export const sendToServer = (level, message) => { export const sendToServer = (level, message) => {
throw new Error('I should not run!');
return `You must mock this function: sendToServer(${level}, ${message})`; return `You must mock this function: sendToServer(${level}, ${message})`;
}; };

View File

@@ -1,6 +1,4 @@
import { vi, describe, it, expect } from 'vitest'; import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
vi.useFakeTimers();
function delay(callback) { function delay(callback) {
setTimeout(() => { setTimeout(() => {
@@ -9,5 +7,22 @@ function delay(callback) {
} }
describe('delay function', () => { describe('delay function', () => {
it.todo('should call callback after delay', () => {}); beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime('2024-02-29');
});
afterEach(() => {
vi.useRealTimers();
});
it('should call callback after delay', () => {
const callback = vi.fn();
delay(callback);
vi.advanceTimersToNextTimer();
expect(callback).toHaveBeenCalled();
expect(new Date()).toBe(null);
});
}); });