Spies For Your Angular Tests TDD
npm install angular-spiesjasmine.createSpy)
angular.spyOnService( serviceName, [ optionalParentSpy, ...])
js
angular
.spyOnService('productService')
`
$3
#### .methods( methodName, ...)
`js
angular
.spyOnService('productService')
.methods('getProducts', 'saveProducts')
`
$3
#### injectSpy( serviceName ) { }
`js
var productCtrl,
productServiceSpy;
beforeEach( injectSpy( function(productService) {
productServiceSpy = productService;
}));
it ('should get products', function(){
var fakeProducts = ['product1', 'product2'];
productServiceSpy.getProducts.and.returnValue( fakeProducts );
productCtrl.loadProducts();
expect(productServiceSpy.getProducts).toHaveBeenCalled();
});
`
$3
#### .asyncMethods( methodName, ...)
`js
angular
.spyOnService('productService')
.methods('someSyncMethod')
.asyncMethods('getProducts', 'saveProducts')
`
Angular spies uses $q in the background to create both the promise as the return value, and exposes its deferred object, and allows you to control the promise's state.
`js
it ('should get products async', function(){
var fakeProducts = ['product1', 'product2'];
var returnedProducts;
productServiceSpy.getDeferred('getProducts').resolve( fakeProducts );
productServiceSpy.getProducts().then(function (products) {
returnedProducts = products;
});
$rootScope.flush();
expect(productServiceSpy.getProducts).toHaveBeenCalled();
expect(returnedProducts).toBe(fakeProducts);
});
`
$3
Lets say for example that you have a generic spy for a data library, with all the CRUD methods defined already:
`js
angular
.spyOnService('dataService')
.asyncMethods('create', 'read', 'update', 'delete')
`
You can use the second parameter of the spyOnService method to declare its parent spies, just add second parameter as an array of spy names you want to extend from (Like angular.module(moduleName, [depenedencies]))
`js
angular
.spyOnService('productService', ['dataService'])
.asyncMethods('createProductByName')
`
Now the spy of productService will have 5 async methods - create, read, update, delete and createProductByName`