我需要使用业力单元测试来测试我的登录过程,但是在执行测试时我遇到了错误。
我的登录控制器代码:
$scope.signin = function (valid) {
if (valid) {
$http.post('/auth/signin', $scope.credentials).success(function (response) {
console.log(response)
// If successful we assign the response to the global user model
$scope.authentication.user = response.user;
localStorage.setItem('token',response.token.logintoken);
// And redirect to the index page
$scope.$dismiss();
}).error(function (response) {
$scope.error = response.message;
});
} else {
$scope.userSigninrequredErr = true;
}
};
Karma测试代码:
(function () {
// Authentication controller Spec
describe('AuthenticationController', function () {
// Initialize global variables
var AuthenticationController,
scope,
$httpBackend,
$stateParams,
$cookieStore,
notify,
$location,
modal;
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Load the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_, _$cookieStore_, _notify_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$cookieStore = _$cookieStore_;
notify = _notify_;
$location = _$location_;
modal = jasmine.createSpyObj('modal', ['show', 'hide']);
// Initialize the Authentication controller
AuthenticationController = $controller('AuthenticationController', {
$scope: scope
});
}));
it('$scope.signin() should login with a correct user and password', function () {
// Test expected GET request {user: 'Fred', token: {logintoken: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9'}}
scope.credentials.user = 'jenson';
scope.credentials.token = {logintoken: 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9'};
$httpBackend.when('POST', '/auth/signin').respond(200, scope.credentials);
scope.signin(true);
$httpBackend.when('GET', /\.html$/).respond('');
$httpBackend.flush();
// Test scope value
expect(scope.credentials.user).toEqual('jenson');
expect($location.url()).toEqual('/dashboard');
});
}
我在执行karma测试后得到了正确的响应,但在devtools控制台中显示以下错误。
TypeError:' undefined'不是一个函数(评估' $ scope。$ dismiss()')
感谢任何帮助。感谢。
答案 0 :(得分:0)
所以问题在于"真实"代码,模态服务正在调用控制器并为您创建一个新的范围,在其上填充$dismiss()
方法,但在单元测试中,您手动调用控制器(使用$controller
服务) ,意思是没有$scope.$dismiss()
函数,因此错误。
相反,你需要做你在真实代码中做的事情,并使用模态服务来实例化你的控制器或至少,模仿模态服务的作用,并在你的新范围上添加一些存根函数,包括$dismiss()
。