vendredi 22 mai 2015

Angular + Jasmine: How to test Controller and Service?

I have such controller (Coffee):

$scope.user =
  email: ''
  password: ''

$scope.signIn = (user) ->
  # Check if form has been filled
  #
  if user.email != '' and user.password != ''
    UserService.signIn(user).success (data) ->
      AuthService.set 'email', data.user.local.email
      AuthService.set 'id', data.user._id
      AuthService.set 'token', data.token
      AuthService.set 'auth', true
      $state.go 'auth.profile'
      return
  return

This is the service (JS):

.factory('UserService', ['$http', function ($http) {
  return {
      signIn: function(user) {
          return $http.post('/user/signin', user);
      }

I can't grasp how to properly test this, this is the code I have so far, but it fails:

describe 'controller Unit Tests', ->

  controller = undefined
  scope = undefined
  signIn = undefined
  UserService = undefined


  beforeEach ->
    module('myApp')

    inject(($controller, $rootScope, _$httpBackend_, UserService) ->
      scope = $rootScope.$new()
      $httpBackend = _$httpBackend_
      service = UserService

      UserService =
        signIn: (user) ->
          success: ->
            {
              "status": "OK",
              "error": "Authed successfully",
              "type": "success",
              "token": "TOKEN STRING",
              "user": {
                "__v": 0,
                "_id": "5512a0dfcbc8ea974647f493",
                "local": {
                  "password": "HASH STRING",
                  "email": "ba@bu.com"
                }
              }
            }
      spyOn(UserService, 'signIn').and.callThrough()

      AuthController = $controller('AuthController', $scope:scope,AuthService:AuthService, UserService:UserService)
    )

    it 'verifies signIn is working', ->

      scope.user['password'] = 'twenty'
      scope.user['email']    = 'ba@bu.de'

      UserService.signIn scope.user

      $httpBackend.whenPOST("/user/signin", scope.user).respond([
        {
          "status": "OK",
          "error": "Erfolgreich Authentifiztiert",
          "type": "success",
          "token": "TOKEN STRING",
          "user": {
            "__v": 0,
            "_id": "5512a0dfcbc8ea974647f493",
            "local": {
              "password": "HASH STRING",
              "email": "dieter"
            }
          }
        }
      ])

      expect(UserService.signIn()).toBeDefined()

What am I doing wrong, what is the best practice to test such a controller / service tandem?

Aucun commentaire:

Enregistrer un commentaire