无法读取属性'spyOn'of null-模拟angularJS单元测试中的承诺

Cannot read property 'spyOn' of null - Mocking a promise in angularJS unit test

本文关键字:单元测试 angularJS 承诺 模拟 spyOn 读取 属性 of null-      更新时间:2023-09-26

我正在尝试模拟一个函数,该函数使用spyOn返回promise,代码如下:

  beforeEach(inject(function($controller, $rootScope, $q) {
    scope = $rootScope.$new();
    q = $q;
    ctrl = $controller('BillingCtrl', {
      $scope: scope,
      $q: q
    });
  }));
  it('should have overlay off when cancel modal is shown', 
    function() {
      var deferred = q.defer();
      deferred.resolve();
      spyOn(scope, 'confirmModal').andReturn(deferred.promise); 
      scope.cancelSubscription(""); //scope.confirmModal is called within here.
      expect(scope.overlayOn).to.equal(true);
  });

这引发了以下错误:

Chrome 37.0.2062 (Mac OS X 10.9.2) Unit: BillingController "before each" hook: workFn FAILED
    TypeError: Cannot read property 'spyOn' of null

scope.confirmModal在这种情况下肯定存在,因为我可以对其进行console.log。

任何建议都将不胜感激!

我想明白了。

Mocha和Jasmine有冲突(我都用了)。

当我移除Mocha时,spyOn功能运行良好。