vendredi 20 juillet 2018

Unable to update an angular components controller from a Jasmine test in Angular 1.x

We have a large app running on angular 1.7 on which we're starting to integrate Jasmine tests (better late than never i guess). I'm playing around with testing some components and ran into an issue trying to update the model from outside of angular (pseudo functional test). In a nutshell, i'm trying to simulate an input[text] update and want the model to get updated as well.

I've distilled everything down as simply as i could. Here is the component:

var myComponent = {
    bindings: {},
    controller: Controller,
    controllerAs: 'vm',
    template: '<input type="text" ng-model="vm.inputValue" value="" />'
};

angular.module('app', []).component('myComponent', myComponent);

function Controller() {
  var vm = this;

  vm.$onInit = _init;
  vm.inputValue = null;

  function _init() {
    vm.inputValue = 'starting value';
  }
} 

Here is my test spec:

var scope;
var myComponentElement;
var myComponentController;

beforeEach(function() {

  angular.mock.module('app');

  inject(function($rootScope, $compile, $componentController) {
    scope = $rootScope.$new();

    myComponentElement = angular.element('<my-component></my-component>');
    myComponentElement = $compile(myComponentElement)(scope);
    myComponentController = $componentController('myComponent');
    myComponentController.$onInit();
  });
});

describe('component test', function() {

  it('should update on external input', function() {
    expect(myComponentController.inputValue).toEqual('starting value');

    var myInput = myComponentElement.find('input');

    myInput.val('new value').trigger('input');

    scope.$digest();

    // this test fails as inputValue is still 'starting value'
    expect(myComponentController.inputValue).toEqual('new value');
  });

});

After doing the val() and trigger(), the components controller isn't seeing the updated value, and the test fails. Even with digest() in there, it still doesn't work. I've tried triggering the update everyway i can think of, but nothing. Fwiw, click events on anchors and buttons seem to work fine, but no luck with input[text]. Any ideas?

I have a plunker with all the code and running the tests. The first test passed with the default input value, but after trying to update the value, the second test fails with the new value:

https://plnkr.co/edit/XNMaETZRuG9x74baa4Zp

Aucun commentaire:

Enregistrer un commentaire