Search code examples
angularjsangular-promisejsdatajs-data-angular

Unit testing promises in js-data-angular models


We use js-data and js-data-angular in our project.

I have the following model:

(function () {
  'use strict';
  angular.module('dash.models')
    .factory('Diagnosis', ['DS', function (DS) {
      function transform(resourcename, attrs, cb) {
        attrs.icd9codes.forEach(function (el) {
          delete el.add;
        });
        cb(null, attrs);
      }

      this.transform = transform;

      return DS.defineResource({
        name: 'diagnosis',
        idAttribute: 'id',
        endpoint: '/diagnosis',
        baseUrl: '/api',
        beforeCreate: transform,
        beforeUpdate: transform
      });
    }]);

}());

And the following call to said model:

    var startEditing = self.startEditing = function(parentScope, diagnosis) {
      Diagnosis.findAll({
        deep:true
      }, {
        endpoint: '/diagnosis/' + diagnosis.id
      }).then(function(d) {
        $scope.diagnosis = d;
        $scope.inScope = true;
      });
    };

In my unit test, I mock the call like this:

var diagDeferred = _$q_.defer();
    diagDeferred.resolve({
      'name': 'Breast',
      'categories': null,
      'id': '026c7cd0-14ef-4312-a8f1-2092107b0e50',
      'icd9codes': [{id: '1', code: '001', description: 'ICD9 Code'}]
    });

    spyOn(Diagnosis, 'findAll').and.returnValue(diagDeferred.promise);

And the actual call is mocked, what doesn't get executed (and I can't find any reliable information on how to get this done) is the function inside the .then of the Diagnosis.findAll

I know the code works, but I need to cover it with unit tests and I'm coming up dry.

Thanks.


Solution

  • I think you forgot to call $scope.digest() in your test. Here is a working fiddle.

    After you call startEditing(), you should call $scope.$digest() so that your mock promise is executed and you can get your data in then block. Hope it helps.