53

我正在使用 Jasmine 创建一个像这样的间谍:

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']);
}));

我希望能够更改authService.

以下是实际测试的设置方式:

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()
    })
})

以下是控制器的设置方式:

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})
        });
    }]);

本质上,我希望能够更改间谍方法的返回值。但是,我不确定我是否正确地使用jasmine.createSpyObj.

4

1 回答 1

87

试试这个。Jasmine 2.0 的 API 已更改:

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

文档:

http://jasmine.github.io/2.0/introduction.html#section-Spies

于 2015-03-06T01:56:31.623 回答