我正在尝试研究如何使用 Karma/Jasmine/Mocha 对我的登录控制器进行单元测试。
我基本上想测试是否返回 200,$auth.login()
然后保存的消息应该等于“成功登录”,否则如果我收到 401,那么返回的消息应该是“登录错误”。
更新
这就是我现在所处的位置。
login.controller.js
function loginCtrl($auth, $scope, $rootScope, $location) {
var vm = this;
vm.login = function() {
var credentials = { email: vm.email, password: vm.password };
// Use Satellizer's $auth service to login
$auth.login(credentials).then(function() {
vm.message = "Successfully logged in!";
}, function(error) {
vm.message = "Error logging in!";
}).then(function(responses) {
$location.path('home');
});
};
}
login.controller.spec.js
describe('Login Controller', function() {
var q, scope, ctrl, auth;
beforeEach(module('app.login'));
beforeEach(inject(function($q, $rootScope, $controller, $auth) {
q = $q;
scope = $rootScope.$new();
ctrl = $controller('loginCtrl', { $scope: scope, SessionService: sessionService, $auth: auth, $q: q });
auth = $auth;
}));
it('should present a successfull message when logged in', function () {
var defer = q.defer();
sinon.stub(auth, 'login')
.withArgs({ email: 'test@test.com', password: 'test_password' })
.returns(defer.promise);
ctrl.login();
defer.resolve();
scope.$apply();
expect(ctrl.message).to.equal('Successfully logged in!');
});
});