mardi 14 juillet 2015

Test multiple sets of mock data in Angular

I'm attempting to test multiple possible situations in my Angular controller through mock JSON data fixtures. My basic setup shown below works perfectly:

beforeEach(inject(function($injector, $controller, $rootScope, _$routeParams_, _playersService_) {
  scope = $rootScope.$new();
  routeParams = _$routeParams_;
  routeParams.playerId = 5;
  playersService = _playersService_;

  $httpBackend = $injector.get('$httpBackend');
  jasmine.getJSONFixtures().fixturesPath = 'base/test/fixtures';

  $httpBackend.whenGET('/api/players/5/info').respond(
    getJSONFixture('info.json')
  );
  $httpBackend.whenGET('/api/players/5/games').respond(
    getJSONFixture('games.json')
  );

  PlayerInfoController = $controller('PlayerInfoController', {$scope: scope, $routeParams: routeParams,
    playersService: playersService});

  scope.$digest();
  $httpBackend.flush();
}));

My issue is that games.json includes a games_status field set to true and my controller handles this one way. I want to also test a mock JSON fixture, we'll call it noGames.json for the case where games_status is false because my controller handles this case differently.

The only way I've found to do this is to repeat all the logic in the beforeEach block above and alter which json file is returned:

$httpBackend.whenGET('/api/players/5/games').respond(
  getJSONFixture('noGames.json')
);

This seems like a TON of repeated code to me. Is there any way to simply load a different JSON fixture within an additional spec without re-running all that beforeEach code?

Aucun commentaire:

Enregistrer un commentaire