Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.