write usecase driven tests systematically for simpler, safer, and more readable code
establishes a pattern of writing tests for simpler, safer, and more readable code.
by defining tests in terms of usecases (given
, when
, then
) your tests are
- simpler to write
- easier to read
- safer to trust
npm install --save test-fns
type Plant = { id: number, hydration: 'DRY' | 'WET' };
const doesPlantNeedWater = (plant: Plant) => plant.hydration === 'DRY';
describe('doesPlantNeedWater', () => {
given('a plant', () => {
when('the plant doesnt have enough water', () => {
const plant: Plant = {
id: 7,
hydration: 'DRY',
};
then('it should return true', () => {
expect(doesPlantNeedWater(plant)).toEqual(true)
})
})
})
})
produces
PASS src/givenWhenThen.test.ts
doesPlantNeedWater
given: a plant
when: the plant doesnt have enough water
✓ then: it should return true (1 ms)
skip running the suite if the condition is not met
describe('your test', () => {
given.runIf(onLocalMachine)('some test that should only run locally', () => {
then.skipIf(onProduction)('some test that should not run against production', () => {
expect(onProduction).toBeFalse()
})
})
})