0

I am trying to test-drive a controller which is bound to a directive.

app.module('App')
.directive('myDirective', function() {
    return {
        templateUrl: '../my-directive.html',
        scope: true,
        bindToController: {
            model: '='
        },
        controller: 'DirectiveCtrl as DirectiveCtrl'
    };
})
.controller('DirectiveCtrl', function() {
    var DirectiveCtrl = this,
        model = DirectiveCtrl.model;

    DirectiveCtrl.resetValue = function() {
        DirectiveCtrl.model = model;
    };
});

In the test,

describe('DirectiveCtrl', function() {
    var DirectiveCtrl,
        model = {
            id: 'id',
            name: 'name'
        };

    beforeEach(module('App'));

    beforeEach(inject(function($controller) {
        DirectiveCtrl = $controller('DirectiveCtrl');
        // code to initialize controller with model value;
    }));

    it('resets the default value', function() {
        DirectiveCtrl.resetValue();
        expect(DirectiveCtrl.model).toEqual(model);
    });
});

I want to initialize the controller in a similar way to how a bounded controller would behave during directive compilation. How can I do this?

1 Answer 1

1

I finally found the solution in angular $controller decorator. The second argument takes an object with bound values.

So the test would be,

describe('DirectiveCtrl', function() {
  var DirectiveCtrl,
    model = {
        id: 'id',
        name: 'name'
    };

  beforeEach(module('App'));

  beforeEach(inject(function($controller) {
    DirectiveCtrl = $controller('DirectiveCtrl', {
        model: model
    });
  }));

  it('resets the default value', function() {
    DirectiveCtrl.resetValue();
    expect(DirectiveCtrl.model).toEqual(model);
  });
});
Sign up to request clarification or add additional context in comments.

Comments

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.