Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mock a service in AngularJS when unit testing with jasmine?

Let's say I have a service shop that depends on two stateful services schedule and warehouse. How do I inject different versions of schedule and warehose into shop for unit testing?

Here's my service:

angular.module('myModule').service('shop', function(schedule, warehouse) {     return {         canSellSweets : function(numRequiredSweets){              return schedule.isShopOpen()                  && (warehouse.numAvailableSweets() > numRequiredSweets);         }     } }); 

Here are my mocks:

var mockSchedule = {     isShopOpen : function() {return true} } var mockWarehouse = {     numAvailableSweets: function(){return 10}; } 

Here are my tests:

expect(shop.canSellSweets(5)).toBe(true); expect(shop.canSellSweets(20)).toBe(false); 
like image 555
KevSheedy Avatar asked Oct 09 '13 14:10

KevSheedy


People also ask

How do you mock a service to inject in a unit test?

1 Answer. Show activity on this post. var service = new MockLoginService(); beforeEachProviders(() => [ provide(TestService, { useValue: service })]); it('should load languages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { tcb . createAsync(LoginComponent).

How do you make a mock function in Jasmine?

Using Jasmine spies to mock code Jasmine spies are easy to set up. You set the object and function you want to spy on, and that code won't be executed. In the code below, we have a MyApp module with a flag property and a setFlag() function exposed. We also have an instance of that module called myApp in the test.

What is Jasmine testing framework and how do you use it for Angular unit testing?

Jasmine is a behavior development testing framework. Unit tests are written using Jasmine and are run to see if individual parts of an application are working correctly. As a result, unit tests will either pass or fail depending on if the code is working correctly or has a bug.


1 Answers

beforeEach(function () {   module(function ($provide) {     $provide.value('schedule', mockSchedule);   }); }); 

Module is a function provided by the angular-mocks module. If you pass in a string argument a module with the corresponding name is loaded and all providers, controllers, services, etc are available for the spec. Generally they are loaded using the inject function. If you pass in a callback function it will be invoked using Angular's $injector service. This service then looks at the arguments passed to the callback function and tries to infer what dependencies should be passed into the callback.

like image 141
Attila Miklosi Avatar answered Sep 27 '22 16:09

Attila Miklosi