mardi 25 août 2015

AngularJS Testing: Extract setup to avoid code duplication

our setup for testing controllers looks always the same, and got duplicated for every test so far. Our setup looks sth like this (coffee script):

describe "Controller: HomeCtrl", ->

  ##################################################
  # SETUP
  ##################################################
  beforeEach module('templates')
  beforeEach module('myApp')

  $controller = $rootScope = $scope = $templateCache = $compile = createController = undefined
  beforeEach inject (_$controller_, _$rootScope_, _$templateCache_, _$compile_) ->
    $rootScope = _$rootScope_
    $controller = _$controller_
    $templateCache = _$templateCache_
    $compile = _$compile_
    $scope = $rootScope.$new()

  beforeEach ->
    createController = ->
      $controller('HomeCtrl', { $scope: $scope, $rootScope: $rootScope })
      $scope.$digest()

  ##################################################
  # TESTS
  ##################################################
  ....

I've played around in putting the whole stuff in a helper method, calling the method with .call(this) and defining all the variables like this.$rootScope, but no matter what, I always got ReferenceError: $rootScope is not defined when $rootScope is referenced from within my tests.

First question: Is it even possible to define a variable inside a method on another scope with this.var and reference this variable with just it's name in the outer scope? As far as I can tell, it's not possible.

Second question: Is there any other way, to put similar setup code in one location, and just include it inside my tests?

Aucun commentaire:

Enregistrer un commentaire