3

我有一个 Angular JS 应用程序,其中包含一个模块和一些服务。我的控制器使用这些服务。在 Jasmine 测试用例中,我使用 Jasmine 的createSpy. 以下是模拟服务:

beforeEach(module(function ($provide) {
    shoppingData = function () {
        getAllItems: jasmine.createSpy('getAllItems');
        addAnItem: jasmine.createSpy('addAnItem');
        removeItem: jasmine.createSpy('removeItem');
   };
   $provide.value('shoppingData', shoppingData);
}));

控制器在getAllItems创建对象后立即调用该函数。我创建了另一个beforeEach创建控制器对象的块。以下是检查是否getAllItems被调用的测试块:

it("Should call getAllItems function on creation of controller", function () {
    expect(shoppingData.getAllItems).toHaveBeenCalled();
});

当我在浏览器上运行规范运行器页面时,测试失败并出现以下错误:TypeError: 'shoppingData.getAllItems' is not a function

我看到了几个类似的例子,这种测试没有任何问题。谁能指出这里缺少什么或出了什么问题?

更新:用失败的部分创建了一个 plunker

4

2 回答 2

3

如果这是真正的代码,这似乎是一个错字。将相应的部分更改为:

shoppingData = {
  getAllItems: jasmine.createSpy('getAllItems'),
  addAnItem: jasmine.createSpy('addAnItem'),
  removeItem: jasmine.createSpy('removeItem')
};

只需将函数更改为对象并更改;for ,

更新 1:

考虑只监视现有对象:

var deferred, _shoppingData;

beforeEach(module('shopping'));

beforeEach(inject(function(shoppingData, $q) {
  _shoppingData = shoppingData;
  deferred = $q.defer();
  spyOn(shoppingData, 'getAllItems').andReturn(deferred.promise);
}));

it('should have called shoppingData.getAllItems', function() {
  expect(_shoppingData.getAllItems).toHaveBeenCalled();
});
于 2013-03-31T20:26:03.003 回答
0

你为什么不试试:

var scope, myController;

beforeEach(inject(function($rootScope, $controller) {
  scope = $rootScope.$new();
  myController = $controller.('controllerName', {
    $scope: scope,
    shoppingData: jasmine.createSpyObj('shoppingData', ['getAllItems', 'addAnItem', 'removeItem'])
  });
}));
于 2013-04-01T17:03:18.103 回答