How to change return value of jasmine spy?

I'm using Jasmine to create a spy like so:

beforeEach(inject(function ($injector) { $rootScope = $injector.get('$rootScope'); $state = $injector.get('$state'); $controller = $injector.get('$controller'); socket = new sockMock($rootScope); //this is the line of interest authService = jasmine.createSpyObj('authService', ['login', 'logout', 'currentUser']);
}));

I'd like to be able to change what's returned by the various methods of authService.

Here are how the actual tests are set up:

function createController() { return $controller('UserMatchingController', {'$scope': $rootScope, 'socket':socket, 'authService': authService });
}
describe('on initialization', function(){ it('socket should emit a match', function() { createController(); expect(socket.emits['match'].length).toBe(1); }); it('should transition to users.matched upon receiving matched', function(){ //this line fails with "TypeError: undefined is not a function" authService.currentUser.andReturn('bob'); createController(); $state.expectTransitionTo('users.matched'); socket.receive('matchedblah', {name: 'name'}); expect(authService.currentUser).toHaveBeenCalled() })
})

Here's how the controller is set up:

lunchrControllers.controller('UserMatchingController', ['$state', 'socket', 'authService', function ($state, socket, authService) { socket.emit('match', {user: authService.currentUser()}); socket.on('matched' + authService.currentUser(), function (data) { $state.go('users.matched', {name: data.name}) }); }]);

Essentially, I'd like to be able to change the return value of spied methods. However, I'm not sure if I'm correctly approaching the problem by using jasmine.createSpyObj.

2

2 Answers

Try this instead. The API changed for Jasmine 2.0:

authService.currentUser.and.returnValue('bob');

Documentation:

We can overwrite it like,

updateService.getUpdate = jasmine.createSpy().and.returnValue('bob')

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like