【问题标题】:How to unit-test angular-toastr using jasmine如何使用 jasmine 对 angular-toastr 进行单元测试
【发布时间】:2015-02-11 10:15:25
【问题描述】:

这是我的控制器中的一个函数,它使用 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});
    });
}

【问题讨论】:

  • 你能发布你的控制器功能吗?
  • 请更新您的问题
  • 您应该真正发布控制器,因为它列出了依赖项
  • 请不要在您的问题中更改您的变量名称。我不得不更新我的答案

标签: angularjs unit-testing karma-jasmine toastr


【解决方案1】:

当您使用 Promise 时,您应该使用 $q 来模拟 myAuthService.login 以返回已解决的 Promise。您还想监视toastr.successMyConfig.setUser。调用$scope.login() 后,您需要解决已解决的promise,然后调用$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

【讨论】:

  • 只有在您使用某种 Toastr 提供程序时它才会起作用,对吗?或者即使你只是使用常规的 JS Toastr,它是否也是一种覆盖这个函数的方法?
  • @Episodex 什么是普通的 js toastr?
  • 当你包含 toastr.js 时,你可以使用全局函数 toastr.info() 例如。据我所知,你不能注入这个。
  • 您需要用服务包装 toastr 或使用常量来对控制器进行单元测试。
  • 我做到了,它工作正常,谢谢。我用了这个答案:stackoverflow.com/a/21565779/219547
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 2019-01-21
相关资源
最近更新 更多