首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用jasmine对angular-toastr进行单元测试

如何使用jasmine对angular-toastr进行单元测试
EN

Stack Overflow用户
提问于 2015-02-11 18:15:25
回答 1查看 5.1K关注 0票数 1

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

代码语言:javascript
复制
$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});
    });
}
EN

回答 1

Stack Overflow用户

发布于 2015-02-11 21:20:52

在使用promise时,您应该使用$q模拟myAuthService.login以返回已解析的promise。您还希望监视toastr.successMyConfig.setUser。在调用$scope.login()之后,您需要解析已解析的promise,然后调用$rootScope.$digest();

代码语言:javascript
复制
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

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28451686

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档