How to change return value of jasmine spy?
79,349
Try this instead. The API changed for Jasmine 2.0:
authService.currentUser.and.returnValue('bob');
Documentation:
http://jasmine.github.io/2.0/introduction.html#section-Spies
Author by
Paymahn Moghadasian
Updated on July 08, 2022Comments
-
Paymahn Moghadasian about 2 years
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
.