Angular: 使用 $auth 模拟登录

Angular: Mock a Login with $auth

我正在研究如何使用 Karma/Jasmine/Mocha 对我的登录控制器进行单元测试。

我基本上想测试 200 是否从 $auth.login() 返回,那么保存的消息应该等于 "successfully logged in", 否则,如果我收到 401,那么返回的消息应该是 "error logging in".

更新

这就是我现在所在的位置。

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!');
  });
});

由于这是您的控制器测试,您可能需要像这样 spyOn 您的服务 ($auth)(在 Jasmine 中)-

var defer = $q.defer();
spyOn('$auth', login).andReturn(defer.promise);
controller.email = 'test@test.com';
controller.password = 'test_password';

controller.login();
defer.resolve();
scope.$apply();

expect($auth.login).toHaveBeenCalledWith({ email: 'test@test.com', password: 'test_password' });
expect(scope.message).toEqual("successfully logged in");

失败案例使用 defer.reject() 和几乎相同的断言格式。

在我看来,您最终会担心 http 相关的 status-codes 或仅在 service 级别而不是 controller 级别的响应。在那里,您将使用 $httpBackend 来模拟响应及其 status-codes 和相应的响应。

编辑

根据我的研究,在 mocha 中,你最终会做类似 -

sinon.stub($auth, 'login')
.withArgs({ email: 'test@test.com', password: 'test_password' })
.returns(defer.promise);

stub的方法。并将调用验证为 -

sinon.assert.calledOnce($auth.login);

其余部分保持不变。消息的断言也将更改为 assert.equal for mocha.

编辑

检查此 fiddle - http://jsfiddle.net/9bLqh5zc/。它使用 'sinon' 作为间谍,使用 'chai' 作为断言