在Jasmine测试中访问控制器的范围

Accessing Scope of controller withing a Jasmine Test

本文关键字:控制器 范围 访问控制 访问 Jasmine 测试      更新时间:2023-09-26

我正在尝试使用Jasmine调用一个Angular Controller方法。我已经写了以下控制器

angular.module('oide.filebrowser')
.controller('FilebrowserController', ['FBFiletreeService', '$rootScope', 'FileService', '$scope', 'FilesystemService', '$modal', function(FiletreeService, $rootScope, FileService, $scope, FilesystemService, $modal){
  var self = this;
  self.formDirPath = function(){
    // Do something...
    return "/home/saurabh";
  };
 })]);

现在,我正在尝试使用Jasmine在作用域上运行formDirPath方法,并使用Karma运行测试。我已经写了以下测试

describe('Filebrowser', function() {
  var scope;
  var controller;
  beforeEach(module('oide.filebrowser'));
  describe('FilebrowserController Test', function() {
    beforeEach(inject(function($controller, $rootScope, $httpBackend, $http){
      scope = $rootScope.$new();
      controller = $controller(
        'FilebrowserController as ctrl', {
          $scope: scope
      });
    }));
    it('should form a correct current dir path', function(){
      expect(scope.formDirPath()).toBe('/home/saurabh');
    });
  });
});

我得到一个错误方法说

"undefined"不是函数(正在评估"scope.formDirPath()")

我是不是做错了什么?我尝试引用以下链接,但对我不起作用:如何将范围变量与";控制器为";Jasmine中的语法?

调用Karma和Jasmine测试的控制器函数

了解问题。这是控制器的语法。更改

expect(scope.formDirPath()).toBe('/home/saurabh');

expect(scope.ctrl.formDirPath()).toBe('/home/saurabh');

修复

问题

formDirPath是控制器的一个函数。

尝试:expect(controller.formDirPath()).toBe('/home/saurabh');