MattDionis
MattDionis

Reputation: 3616

How to pull data from JSON fixture in mock Angular service

I have created the below mock Angular service to test a controller. When I run my tests I get the error: Unexpected request: GET ./fixtures/stats.json.

mock.players.service.js:

'use strict';

angular.module('mockPlayersService', [])
  .factory('playersService', ['$http', '$q',
    function($http, $q) {
      var playersService = {};

      playersService.stats = $http.get('./fixtures/stats.json');

      playersService.getStats = function() {
        var defer = $q.defer();
        defer.resolve(this.stats);
        return angular.extend({$promise: defer.promise}, this.stats);
      };

      return playersService;
    }]);

Is there something I need to do in my controller spec to tell my tests to expect this GET request, and/or do I need to declare the fixtures path in my karma.config.js files array?

EDIT: Some more info to show my current (working) setup:

playersService.stats = {
  'firstName': 'John',
  'middleName': 'James',
  'lastName': 'Doe',
  'city': 'Cleveland',
  'state': 'OH',
};

playersService.getStats = function() {
  var defer = $q.defer();
  defer.resolve(this.stats);
  return angular.extend({$promise: defer.promise}, this.stats);
};

I simply want to move that current playersService.stats object out into a JSON fixture.

Upvotes: 1

Views: 1260

Answers (1)

Robert Moskal
Robert Moskal

Reputation: 22553

Based on your approach the easiest thing would be to make karma serve your fixture files. In your karma.conf files stanza you can add something like this:

  { pattern:  './fixtures/*.json',
    watched:  true,
    served:   true,
    included: false }

I think karma serves files from a root called base, you may need to play with the url you are giving to $http.

I don't quite get why you bother with a MockService sistering your actual one. It seems like a very heavy weight approach. The more usual thing to do is to use your actual service and mock the backend. Something like this in your tests:

before(inject(function( $httpBackend, playersService) {
    o = playersService;
    back = $httpBackend;

  back.whenGET('/therealPath').respond({});


}));

You'd still need a way to get your fixture files loaded, but you could install karma-read-json and then follow a pattern like this:

var valid_respond = readJSON('./fixtures/stats.json');
$httpBackend.whenGET('/therealPath').respond(valid_respond);

Upvotes: 3

Related Questions