我需要使用karma單元測試來測試我的登錄過程,但是我在執行測試時遇到了錯誤。對於登錄
我的控制器代碼:
$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;
}
};
噶測試代碼:
(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');
});
}
我得到執行因果報應測試,但下面的錯誤是顯示在devtools控制檯後,正確的反應。
TypeError: 'undefined' is not a function (evaluating '$scope.$dismiss()')
任何幫助表示讚賞。謝謝。
你可以顯示'AuthenticationController'代碼的其餘部分 - '$ scope。$ dismiss()'定義在哪裏?或者這個控制器通常通過模態服務運行? – GregL
$ dismiss已在模態範圍內使用,在控制器中沒有使用mroe函數 –
$ dismiss(reason)(類型:函數) - 一種可用於消除模態並傳遞原因的方法。 –