1

Controller

function SomeController(someService) {
  const $ctrl = this;

  activate();

  function activate() {
    someService.retrieveSomeData($ctrl.criteria).then(doSomething);
  }

  function doSomething(response) {
    $ctrl.result = response.data;
  }
}

Test

describe('SomeController', () => {

  beforeEach(module('myModule'));

  let $controller;

  beforeEach(inject((_$controller_,) => {
    $controller = _$controller_;
  }));

 it('tests $controller properties', () => {
    const $scope = {};
    const controller = $controller('SomeController', { $scope });
  });
});

Here I want to sent $ctrl.criteria while initializing my controller so I can test $ctrl.result afterwards.

4
  • you could just have const controller = $controller('SomeController') where controller will have this available Commented Aug 24, 2016 at 10:25
  • As you can see, the activate() method executes on initialization, I tried setting it after initialization, but the activate() method is already fired by then. Commented Aug 24, 2016 at 10:28
  • @AbubakrDar is this a component's controller? Commented Aug 25, 2016 at 16:01
  • No, its not @SiddharthPandey. It is used to show a customized $mdDialog. Commented Aug 25, 2016 at 16:36

2 Answers 2

0

try this:

describe('SomeController', () => {

  beforeEach(module('myModule'));

  let $controller;

  beforeEach(inject((_$controller_,) => {
    $controller = _$controller_;
  }));

 it('tests $controller properties', () => {
    const scope = {
      criteria : {id: 1}
    };
    const controller = $controller('SomeController', { $scope : scope });
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I tried doing that, but criteria was still undefined.
What I figured out was, you pass in the controller properties as a third argument.
0

I'm not sure, if its a general solution or specific to this case, but to pass in the locals of a controller, you have the third aurgument of $controller. At least, it worked for me.

Test

describe('SomeController', () => {

  beforeEach(module('myModule'));

  let $controller;

  beforeEach(inject((_$controller_,) => {
    $controller = _$controller_;
  }));

 it('tests $controller properties', () => {
    const $scope = {};
    const criteria = {id: 1};
    const controller = $controller('SomeController', { $scope }, { criteria });
  });
});

1 Comment

I'm amazed that I couldn't find this in any documentation or any of the easily available content. Such a simple solution. Wasted hours on it yesterday.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.