1

我正在尝试研究如何使用 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!');
  });
});
4

1 回答 1

1

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

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在我看来,您最终只会在service级别而不是级别上担心相关的状态代码或响应controller。在那里,您可以使用$httpBackend它们的状态代码和相应的响应来模拟响应。

编辑

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

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

stub方法。通话验证为 -

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

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

编辑

签出这个小提琴 - http://jsfiddle.net/9bLqh5zc/。它使用“sinon”作为间谍,使用“chai”作为断言

于 2016-01-11T17:20:43.150 回答