Skip to content

Instantly share code, notes, and snippets.

@kylewhitaker
Last active September 8, 2017 23:53
Show Gist options
  • Save kylewhitaker/c67a049988c1673d6c12fd9c27aa4a6d to your computer and use it in GitHub Desktop.
Save kylewhitaker/c67a049988c1673d6c12fd9c27aa4a6d to your computer and use it in GitHub Desktop.
Harness the power of Jasmine's createSpy() and createSpyObj() functions to mock & spy all at once!
import { SomeComponent } from './some.component.js';
describe('SomeComponent:', () => {
let component: SomeComponent;
let mockDepOne: any;
let mockDepTwo: any;
beforeEach(() => {
mockDepOne = {
doSomething: jasmine.createSpy('doSomething').and.returnValue('0123456789')
};
mockDepTwo = jasmine.createSpyObj('DepTwo', ['doSomethingElse']);
component = new SomeComponent(mockDepOne, mockDepTwo);
});
describe('someMethod', () => {
describe('called with true', () => {
// notice we do not require a spyOn() method
it('should call depOne.doSomething', () => {
component.someMethod(true);
expect(mockDepOne.doSomething).toHaveBeenCalled();
});
});
describe('called with false', () => {
// notice we do not require a spyOn() method
it('should call depOne.doSomething', () => {
component.someMethod(false);
expect(mockDepTwo.doSomethingElse).toHaveBeenCalled();
});
});
});
});
import { DepOne, DepTwo } from './dependencies';
export class SomeComponent {
constructor(
private depOne: DepOne,
private depTwo: DepTwo
) { }
someMethod(someCondition: boolean): void {
if (someCondition) {
this.depOne.doSomething();
} else {
this.depTwo.doSomethingElse();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment