【问题标题】:Angular unit test that calls a service调用服务的 Angular 单元测试
【发布时间】:2014-05-28 15:16:37
【问题描述】:

我有一个非常简单的控制器,它有一个调用服务方法来填充的范围变量。我正在尝试编写测试以确保填充此变量,但我收到错误 Expected spy find to have been called.

如何使用 spy 为服务块编写此单元测试?

describe('StuffCtrl', function() {

    beforeEach(module('web'));

    var scope, ctrl, stuff;

    beforeEach(inject(function($rootScope, $controller, Stuff) {
      scope = $rootScope.$new();
      stuff = Stuff;
      ctrl = $controller('StuffCtrl', {$scope: scope, Stuff: stuff});
    }));

it('should fetch all the stuff', function() {

    // Mock the Stuff.find service
    spyOn(stuff, 'find');

    // ERROR ON THIS LINE: Expected spy find to have been called.
    expect(stuff.find).toHaveBeenCalled();
    expect(scope.stuff).toBeDefined();
  });
...

控制器

angular.module('web').controller('StuffCtrl',function($scope, $log, $routeParams, $location, Stuff){

  $scope.stuff = Stuff.find();

});

东西服务

module.factory("Stuff", ['LoopBackResource', '$injector', function(Resource, $injector) {

  var R = Resource(
      urlBase + "/stuff/:id",
      { 'id': '@id' },
      {"find": {
          url: urlBase + "/stuffs",
          method: "GET",
          isArray: true,
        }
      });


    return R;
  }]);

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    试试这个

    describe('StuffCtrl', function() {
    
        beforeEach(module('web'));
    
        var scope, ctrl, stuff;
    
        beforeEach(inject(function($rootScope, $controller, Stuff) {
          scope = $rootScope.$new();
          stuff = Stuff;
          // Mock the Stuff.find service
          spyOn(stuff, 'find');
          //you're instanciating the controller here so find will get executed.
          //you need to mock find before.
          ctrl = $controller('StuffCtrl', {$scope: scope});
        }));
    
    it('should fetch all the stuff', function() {
        expect(stuff.find).toHaveBeenCalled();
        expect(scope.stuff).toBeDefined();
      });
    ...
    

    【讨论】:

    • 哦,好吧,这是有道理的。所以基本上我需要在实例化控制器之前调用 spy ,除非我有一个在我的控制器中调用的函数。在这种情况下,我可以在单元测试中调用该控制器函数之前随时调用 spyOn。对吗?
    • 就是这样,$controller 的作用并不明显,但是是的,它实例化了您的控制器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 2020-03-17
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多