I am trying to get familiar with testing an AngularJS application. While testing component logic is clear more or less, I have a trouble with html templates and model binding, because I'd like to test html binding together with controller's logic.
Test is run by karma in a real browser, so testing environment supports DOM.
It looks like it's not possible, doesn't it?
describe('sign-up', function () {
angular.mock.module('myApp');
angular.mock.inject(function($componentController, $rootScope, $document) {
let scope = $rootScope.$new();
let signUp = $componentController('signUp', {$scope: scope});
console.log(`signup = ${signUp}`);
for (let [k,v] of signUp) {
// there is no field signUp.firstName
// but inside the controller code referencing
// this.firstName is working
console.log(`signup.${k} = ${v}`);
}
// jquery cannot find #firstName node
// $('#firstName').val('dan') gets the same outcome
$document.find('#firstName').val('dan');
expect($document.find('#firstName').val()).toBe('dan');
// without DOM form submission is not possible
});
});
});
Controller component:
angular.
module('myApp').
component('signUp', {
templateUrl: template,
controller: [
function () {
this.form = {};
var self = this;
}]});
Template:
<form novalidate name="$ctrl.form" >
<div class="form-group">
<input type="text" class="form-control"
ng-model="$ctrl.firstName"
required
name="firstName"
id="firstName"
/>
</div>
</form>
$compile
service.$componentController
will not help you in testing your component templates. Take a look at my answer here. The first example shows how to test template (called "should render template"). – Langton