如何使用茉莉花单位测试角度

时间:2015-02-11 10:15:25

标签: angularjs unit-testing karma-jasmine toastr

这是我的控制器中的一个功能,它使用Toastr进行通知。如何在我的Jasmine单元测试中测试Toastr的功能。

$scope.login = function(user) {
    $scope.user = user;
    MyAuthService.login($scope.user)
    .then(function(response) {
        MyConfig.setUser(response.data.data);
        toastr.success('Welcome', 'Login!',{closeButton: true});
    });
}

1 个答案:

答案 0 :(得分:3)

当您使用promises时,您应该使用$ q来模拟myAuthService.login以返回已解决的承诺。您还想监视toastr.successMyConfig.setUser。致电$scope.login()后,您需要解决已解决的承诺,然后致电$rootScope.$digest();

describe('MyCtrl', function() {
  var createController, $scope, $rootScope, myAuthService, myConfig, toastr, deferred;

  beforeEach(module('app'));

  beforeEach(inject(function($controller, _$rootScope_, $q) {
    $rootScope = _$rootScope_;
    deferred = $q.defer();

    myConfig = {
      setUser: function (data) {

      }
    };

    spyOn(myConfig, 'setUser');

    myAuthService = {
      login: function () {

      }
    };

    spyOn(myAuthService, 'login').and.returnValue(deferred.promise);

    toastr = {
      success: function (message, title, options) {

      }
    };

    spyOn(toastr, 'success');

    $scope = $rootScope.$new(); 

    createController = function() {
      return $controller('MyCtrl', 
        { 
           $scope: $scope, 
           MyAuthService: myAuthService,
           MyConfig: myConfig,
           toastr: toastr
        });
    };
  }));

  it('login sets user in config and shows success toastr', function() {
    //Arrange
    createController();

    var response = {
      data: {
        data: {
          username: 'test'
        }
      }
    };

    $scope.user = {
      username: 'test'
    };

    //Act
    $scope.login();
    deferred.resolve(response);
    $rootScope.$digest();

    //Assert
    expect(myAuthService.login).toHaveBeenCalledWith($scope.user);
    expect(myConfig.setUser).toHaveBeenCalledWith(response.data.data);
    expect(toastr.success).toHaveBeenCalledWith('Welcome', 'Login!', {closeButton: true});
  });
});

Plunkr