Skip to content

Instantly share code, notes, and snippets.

@kylefox
Created March 18, 2018 21:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylefox/f378ea024540a1b15fa3701755e10c26 to your computer and use it in GitHub Desktop.
Save kylefox/f378ea024540a1b15fa3701755e10c26 to your computer and use it in GitHub Desktop.
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' });
});
});
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