1

I am trying to simulate user actions and test AngularJS controller reaction on them.

describe('Testing a controller component', function () {
    beforeEach(inject(function ($compile, $rootScope, $httpBackend, $templateCache) {
        scope = $rootScope.$new();
        element = angular.element('<sign-up></sign-up>');
        element = $compile(element)(scope);
        scope.$digest();
        controller = element.controller('signUp');
        scope.$apply();
    }));

    it('should render template', function () {
        element.find('input').val('123');
        scope.$digest();
        expect(controller.firstName).toBe('123');
    });
});

The test fails due the model field is not updated.

Expected undefined to be '123'.
        at UserContext.<anonymous> (tests/calculator.controller.test.js:54:42)

I know it's against the AngualrJs approach, but I want to use it for testing.

Daniil Iaitskov
  • 5,525
  • 8
  • 39
  • 49

1 Answers1

1

More "AngualrJS"-way to simulate user's input here is to access the input's ngModelController and changing the view value by using $setViewValue() method. Something like this should work:

it('should reflect to the users input', function () {
    var input = element.find('input');
    var ngModelCtrl = input.controller('ngModel');
    ngModelCtrl.$setViewValue('Dan');
    expect(controller.firstName).toBe('Dan');
});

But if you still want to proceed with your approach then you have to trigger one of the updateOn events on your input element (using triggerHandler method) so the value will be applied to the $modelValue:

it('should reflect to the users input', function () {
    element.find('input').val('123').triggerHandler('input');
    expect(controller.firstName).toBe('123');
});
Stanislav Kvitash
  • 4,614
  • 18
  • 29
  • the second solution is just what I was looking for. It complements DOM integration. Otherwise it would be strange why outside events are handled and element.click() is working out of the box, but the model is left aside. – Daniil Iaitskov Jan 17 '18 at 09:41