gpt4 book ai didi

angularjs - 如何监视模拟服务 AngularJS/Karma?

转载 作者:行者123 更新时间:2023-12-03 14:30:26 24 4
gpt4 key购买 nike

'use strict'

webApp.controller 'NavigationController', [
'$scope'
'$rootScope'
'UserService'
($scope, $rootScope, UserService) ->
$scope.init = ->
UserService.isAuthenticated().then (authenticated) ->
$scope.isAuthenticated = authenticated

$scope.init()
]

我想写一个测试到 spyOn如果 isAuthenticated来自 UserService .在我的 beforeEach , 我有:
  beforeEach ->
module 'webApp'

inject ($injector) ->
$httpBackend = $injector.get '$httpBackend'
$q = $injector.get '$q'
$rootScope = $injector.get '$rootScope'

$scope = $rootScope.$new()
$controller = $injector.get '$controller'

UserServiceMock =
isAuthenticated: ->
deferred = $q.defer()
deferred.promise


controller = $controller 'AboutUsController',
'$scope': $scope
'$rootScope': $rootScope
'UserService': UserServiceMock

$httpBackend.whenGET('/api/v1/session').respond 200

任何帮助将不胜感激..谢谢

最佳答案

您可以在 UserServiceMock 中调用 isAuthenticated 时将变量设置为 true .例如。:

var isAuthenticatedCalled;
var controller;

beforeEach(function() {
isAuthenticatedCalled = false;

module('webApp');
inject(function($injector) {

//...

UserServiceMock = {
isAuthenticated: function() {
isAuthenticatedCalled = true;
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
}
};
controller = $controller('AboutUsController', {
'$scope': $scope,
'$rootScope': $rootScope,
'UserService': UserServiceMock
});

// ...

});
});

it('should call isAuthenticated', function() {
expect(isAuthenticatedCalled).toBe(true)
});

或者,您可以使用 Jasmine 的 spyOn功能。
UserServiceMock = {
isAuthenticated: function() {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
}
};

spyOn(UserServiceMock, 'isAuthenticated');

在你的测试中你可以做
it('should call isAuthenticated', function() {
expect(UserServiceMock.isAuthenticated).toHaveBeenCalled()
});

关于angularjs - 如何监视模拟服务 AngularJS/Karma?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25528617/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com