【发布时间】:2015-08-12 14:26:52
【问题描述】:
我一直在尝试为 Spring-boot 教程中的 js 代码编写单元测试: http://spring.io/guides/tutorials/spring-security-and-angular-js/
我想要做的是把来自/user 的响应伪装成 200 响应,这样我就可以测试控制器是否设置了$rootScope.authenticated = true
这里是 hello.js:
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'home.html',
controller : 'home'
}).otherwise('/');
}).controller('navigation', function($rootScope, $scope, $http, $location, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
$http.get('/user').success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
}).error(function() {
$rootScope.authenticated = false;
});
$scope.credentials = {};
$scope.logout = function() {
$http.post('/logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
}).controller('home', function($scope, $http) {
$http.get('/resource').success(function(data) {
$scope.greeting = data;
})
});
我正在尝试模拟来自端点上 GET 调用的响应:/user 并强制控制器定向到经过身份验证的用户的流。
对应的茉莉花规格:
describe('UiApplicationTest', function() {
var scope;
var $httpBackend, $controller;
beforeEach(module('hello'));
beforeEach(inject(function(_$rootScope_, _$controller_, _$httpBackend_) {
$controller = _$controller_;
$httpBackend = _$httpBackend_;
scope = _$rootScope_;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('Should authentication details be provided', function() {
beforeEach(function() {
// Taking care for requests not in the scope of the test
$httpBackend.whenGET(/\.html$/).respond('');
// Mocking request under test
$httpBackend.whenGET('/user').respond(200, 'user');
$controller('navigation', { $scope: scope });
// Launching the request
$httpBackend.expectGET('/user');
$httpBackend.flush();
});
it('user shall grant access', function() {
expect(scope.authenticated).toBe(true);
});
});
});
问题是我没有得到预期的结果。断言是:
Expected false to be true.
我已经花了几个小时阅读各种手册和帖子。显然我不明白这里的东西。有人能指出我的错误吗?
【问题讨论】:
标签: angularjs jasmine spring-boot