Created
March 18, 2018 21:48
-
-
Save kylefox/f378ea024540a1b15fa3701755e10c26 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Customer from 'Customer'; | |
import API from 'API'; | |
import Spies from 'Spies'; | |
beforeEach(() => { | |
Spies.start(); | |
}); | |
afterEach(() => { | |
Spies.stop(); | |
}); | |
describe('find', () => { | |
test('retrieves an existing customer', () => { | |
Customer.find(1); | |
expect(Spies.API.get).toHaveBeenCalledWith('https://api.test/customers', { id: 1 }); | |
}); | |
}); | |
describe('save', () => { | |
test('saves a new customer', () => { | |
Customer.save({ name: 'Kyle' }); | |
expect(Spies.API.post).toHaveBeenCalledWith('https://api.test/customers', { name: 'Kyle' }); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Customer from 'Customer'; | |
import API from 'API'; | |
const createSpy = (object, methods) => { | |
const spy = {}; | |
spy.start = () => { | |
methods.forEach((method) => { | |
spy[method] = jest.spyOn(object, method); | |
}); | |
} | |
spy.stop = () => { | |
methods.forEach((method) => { | |
spy[method].mockRestore(); | |
}); | |
} | |
return spy; | |
} | |
const _spies = new Map(); | |
// Configure the objects/methods you want to spy on. | |
_spies.set('Customer', createSpy(Customer, ['find', 'save'])); | |
_spies.set('API', createSpy(API, ['get', 'post', 'put'])); | |
_spies.set('Console', createSpy(global.console, ['error', 'warn'])); | |
const Spies = { | |
start: () => _spies.forEach((spy, name) => spy.start()), | |
stop: () => _spies.forEach((spy, name) => spy.stop()), | |
}; | |
_spies.forEach((spy, name) => { | |
Spies[name] = spy; | |
}); | |
export default Spies; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment