Mocking ngResource in Angular Unit Tests

I have ngResourceMockFactory that looks like this:

 (function() { 'use strict'; angular.module('app') .factory('NgResourceMock', ngResourceMockFactory) ; ngResourceMockFactory.$inject = []; function ngResourceMockFactory() { function NgResourceMock() { var context = this; context.$promise.then = function() { context.prototype.$promise.then.apply(context, arguments); }; context.$promise.finally = function() { context.prototype.$promise.finally.apply(context, arguments); }; } NgResourceMock.prototype.$promise = { then: function(onSuccess, onError) { this.$promise.onSuccess = onSuccess; this.$promise.onError = onError; }, finally: function(onComplete) { this.$promise.onComplete = onComplete; } }; return NgResourceMock; } })(); 

I embed this in my tests in beforeEach like this:

 beforeEach(inject(function(NgResourceMock) { ngResourceMock = new NgResourceMock(); })); 

then I use it as follows:

 describe('initiateWorkflow function', function() { beforeEach(function() { vm.player = {id: 123}; spyOn(dataService, 'initiateWorkflow').and.returnValue(ngResourceMock); vm.initiateWorkflow(); }); it('should call dataService.initiateWorkflow', function() { expect(dataService.initiateWorkflow).toHaveBeenCalledWith({playerId: vm.player.id}, {}); }); }); 

but I see the following error:

 TypeError: 'undefined' is not an object (evaluating 'context.prototype.$promise') 

This makes me think that something is wrong with my ngResourceMockFactory , but I'm not sure what it is.

+5
javascript angularjs jasmine karma-jasmine
source share
2 answers

I don't know if this can help, but if you are trying to evaluate asynchronous operations in your tests, you can use the done() method in Jasmine.

According to their documentation:

 beforeEach(function(done) { setTimeout(function() { value = 0; done(); }, 1); }); 

passing done as the beforeEach callback parameter, any test run after each of them has to wait until the done() function is called.

Source: Jasmine (asynchronous support section).

Hope this helps.

+4
source share

Here is the solution to your problem.

The TypeError: 'undefined' is not an object (evaluating 'context.prototype.$promise') error occurs when you try to call a promise object before calling the function in which it is defined or in which your parent function is defined.

Here returnValue(ngResourceMock) directly calls the function without context, and the parameters must be defined.

Therefore, you can try adding another beforeEach , for example

 beforeEach(angular.mock.module(app)); 

to download your application module

There may be one and the same concept related to your problem here.

Hope this helps you.

+2
source share

All Articles