Saurabh Sood
Saurabh Sood

Reputation: 233

Accessing Scope of controller withing a Jasmine Test

I am trying to call an Angular Controller method using Jasmine. I have written the following 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";
  };
 })]);

Now, I am trying to run the formDirPath method on the scope with Jasmine, and run the tests with Karma. I have written the following test

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');
    });
  });
});

I get an error method saying

'undefined' is not a function (evaluating 'scope.formDirPath()')

Am I doing something wrong here? I tried referring the following links, which did not work for me: How to use scope variables with the "Controller as" syntax in Jasmine?

Call a controller function from Karma and Jasmine testing

Upvotes: 0

Views: 1236

Answers (2)

Queequeg
Queequeg

Reputation: 131

formDirPath is a function of the controller.

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

Upvotes: 0

Saurabh Sood
Saurabh Sood

Reputation: 233

Understood the problem. It is the controllerAs syntax. Changing

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

to

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

fixes the problem

Upvotes: 1

Related Questions