运行业力测试时获取未定义的方法

时间:2019-05-30 06:16:18

标签: javascript angularjs unit-testing

我在控制器内部创建了一个scope方法,当按下按钮时该方法正在执行。我在写单元测试用例。我已经将模块注入到beforeEach块中,并创建了spyon我的作用域函数,然后在“ it”方法中使用它,并检查是否调用了它。但是找不到错误作为方法。

控制器

    'use strict';

angular.module('myApp.view1', ['ngRoute'])

  .config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/view1', {
      templateUrl: 'view1/view1.html',
      controller: 'View1Ctrl'
    });
  }])

  .controller('View1Ctrl', ['$scope',View1Ctrl])

  function View1Ctrl($scope) {
    $scope.user = {
      name: '',
      last: ''
    }
    $scope.showFormData = function() {
      $scope.formData = $scope.user.name + $scope.user.last;
    }
  }

spec.js

   'use strict';

describe('myApp.view1 module', function () {

  var $controller, $rootScope;
  beforeEach(module('myApp.view1'));

  beforeEach(inject(function (_$controller_, _$rootScope_) {
    $controller = _$controller_;
    $rootScope = _$rootScope_;
  }));

  describe('view1 controller', function () {

    var $scope, controller, formData;
    beforeEach(function () {
      $scope = $rootScope.$new();
      controller = $controller('View1Ctrl', {
        $scope: $scope
      });
      spyOn(controller, 'showFormData');
    });

    it('should check for the show form details', function () {
      $scope.user.name = "Sandeep";
      $scope.user.last = "Gupta";
      expect($scope.showFormData).toHaveBeenCalled();
      expect($scope.user.name + $scope.user.last).toEqual(firstname);
    });

  });
});

需要帮助来解决此问题。

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试监视控制器的showFormData方法:

  spyOn(controller, 'showFormData');

但是,控制器上不存在showFormData,它是控制器作用域的一种方法。

您需要使用:

  spyOn($scope, 'showFormData');

同样重要的是要知道您需要对spyOn和Expect(...)。toHaveBeenCalled()使用同一对象。在您的情况下,您在监视controller.showFormData(),但希望已调用$ scope.showFormData()。

相关问题