mardi 4 août 2015

How to assign a controller to an element at run-time in a unit-test?

Suppose I register a state like so:

module.config(function($stateProvider) {
  $stateProvider.state('case.summary', {
    url: '/summary',
    controller: summaryController,
    controllerAs: 'ctrl',
    templateUrl: 'cases/view/summary/summary.tpl.jade',
    data: {
      title: 'Case Summary'
    }
  });
});

Now I want to create a unit test that tests several assertions on the rendered page. I'd like to do this in a unit test as opposed to an e2e test, if possible.

I think that I should be able to do this without having to even use the ui-router API. Ideally, I'd like to fetch the template from the template-cache, then compile it, assigning the same controller as is registered with that state.

My problem is that (unless I missed something) I can't find anything in the Angular API that will give me a way to programmatically compiling a template and assigning a controller at run-time. $compile accepts an HTML template (string) as its argument, then returns a function that accepts a scope as it's argument. There is no place to bind it to a controller.

As far as I can tell, I have to either wrap my template in "..." before I compile it, or create a directive that combines that template and controller and then compile "" to get the result I want to examine.

If anyone knows a better way to do this please let me know.

Aucun commentaire:

Enregistrer un commentaire