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);
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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With