Bend the JS rules

in Angular applications

Dr. Gleb Bahmutov PhD

@bahmutov


Kensho 

Boston / NY / SF

Hello, <list application>

Simple Angular app

<script src="node_modules/angular/angular.js"></script>
<script>
  angular.module('HelloApp', [])
    .controller('HelloController', function ($scope) {
      $scope.names = ['John', 'Mary'];
    });
</script>
<body ng-app="HelloApp" ng-controller="HelloController">
  <h2>Hello</h2>
  <ul>
    <li ng-repeat="name in names track by $index">{{ name }}</li>
  </ul>
</body>

Add data from console

Extend method from console

Debug method from console

Ajax without a server

.controller('HelloController', function ($scope, $http) {
  $scope.names = ['John', 'Mary'];
  $scope.addName = function () {
    $http.get('/new/name').then(function (newName) {
      $scope.names.push(newName);
    });
  };
});

Mock $http

.controller('HelloController', function ($scope, $http) {
  $scope.names = ['John', 'Mary'];
  $scope.addName = function () {
    $http.get('/new/name').then(function (newName) {
      $scope.names.push(newName);
    });
  };
});

Loading Angular app from Node

Use a private function inside Angular closure

Test public function in Angular application with ng-describe

// app.js
angular.module('HelloApp', [])
  .controller('HelloController', function ($scope) {
    $scope.names = ['John', 'Mary'];
  });
// spec.js
ngDescribe({
  modules: 'HelloApp',
  controller: 'HelloController',
  tests: function (deps) {
    it('has names', function () {
        expect(deps.names).toEqual(['John', 'Mary']);
    });
  });
});

Private function inside Angular closure

(function () {
  function nextName() {
    return 'World';
  }
  angular.module('HelloApp', [])
    .controller('HelloController', function ($scope) {
      $scope.names = ['John', 'Mary'];
      $scope.addName = function () {
        $scope.names.push(nextName());
      };
    });
}());

How do we test 'nextName()' ?

Test a private function inside Angular closure

// next-name-spec.js
var ngDice = require('ng-dice');
ngDice({
  name: 'app',
  file: __dirname + '/app.js',
  extract: 'nextName()',
  tests: function (codeExtract) {
    it('returns next name', function () {
      var nextName = codeExtract();
      console.assert(nextName() === 'World');
    });
  }
});

Bend the JS Rules

in Angular applications

Thank you

Kensho Boston / NYC / SF

Bend the JS rules in Angular application

By Gleb Bahmutov

Bend the JS rules in Angular application

Bend the JavaScript rules for powerful Angular applications: access the controller logic from the browser console, mock on the fly, load app from Node, unit test private functions. Presented at ManhattanJS meetup.

  • 7,593