mercredi 19 septembre 2018

Karma+AngularJS - combine template and controller

Here is my scenario:

I have a view with a lot of components. View is given a controller (via ui-router state config) Based on user interactions with those components, view's controller produces some data which then gets sent to the server.

What I want to do in my tests is to mimic user's activity by using element.triggerHandler('click') and then use $httpBackendto ensure correct payload was prepared.

I'm able to do similar things with single directive or component, but is it possible to do with custom template and controller?

This is my attempt:

const template = $templateCache.get('view-template.html');
let scope = $rootScope.$new();
let element = angular.element(template);
$compile(element)(scope);

let controller = $controller('ViewController', {
    '$scope': scope,
    '$element': element
});
scope.$digest();

Then I'm trying something like this (a bit messy but this one worked for component in another test)

angular.element($(element).find('#myButton')).triggerHandler('click');
scope.$digest();

In view-template.html I have:

<button ng-click="vm.test()" id="myButton">Click me</button>

vm is from controllerAs originally used when declaring states. When running above code, test() in controller is not executed. Is it possible to have it working?

I know that it is a bit more than unit test, but as I don't need server for this I thought that using karma would be good idea.

Aucun commentaire:

Enregistrer un commentaire