Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created May 25, 2016 15:59
Show Gist options
  • Save kentcdodds/576c16d2069b3535aa4d7435082b186a to your computer and use it in GitHub Desktop.
Save kentcdodds/576c16d2069b3535aa4d7435082b186a to your computer and use it in GitHub Desktop.
Nested Unit Tests - An Anti-Pattern

Nested Unit Tests: An Anti-Pattern

This is an example of what I'm talking about in my 3 minute podcast here

import test from 'ava'
import Customers from './Customers'
import getMockCustomers from './Customers/mocks'
test('getCustomers: should return the existing customers', t => {
const mockCustomers = initializeCustomers()
const customers = Customers.getCustomers()
t.deepEqual(customers, mockCustomers)
cleanupCustomers()
})
test('setCustomers: should set the customers array', t => {
initializeCustomers([])
const mockCustomers = getMockCustomers()
Customers.setCustomers(mockCustomers)
const customers = Customers.getCustomers()
t.deepEqual(customers, mockCustomers)
cleanupCustomers()
})
function initializeCustomers(initialCustomers = getMockCustomers()) {
Customers.setCustomers(initialCustomers)
return initialCustomers
}
function cleanupCustomers() {
Customers.setCustomers([])
}
import Customers from './Customers'
import getMockCustomers from './Customers/mocks'
describe('Customers', () => {
let mockCustomers
beforeEach(() => {
Customers.setCustomers([]) // initialize to empty for most tests
mockCustomers = getMockCustomers() // have mock customers available
})
afterEach(() => {
Customers.setCustomers([]) // clean up just in case
})
describe('getCustomers', () => {
beforeEach(() => {
Customers.setCustomers(mockCustomers)
})
it('should return the existing customers', () => {
const customers = Customers.getCustomers()
expect(customers).to.be.eql(mockCustomers)
// questions you must ask if you're not familiar with this file and it's bigger:
// - where does `mockCustomers` come from?
// - what make `getCustomers` return the mockCustomers?
})
})
describe('setCustomers', () => {
it('should set the customers array', () => {
Customers.setCustomers(mockCustomers)
const customers = Customers.getCustomers()
expect(customers).to.be.eql(mockCustomers)
// question you must ask if you're not familiar with this file and it's bigger:
// - where does `mockCustomers` come from? What is it initialized as?
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment