Test method of an Angularjs controller using Karma, Mocha, Chai, Sinon

Asked

Viewed 117 times

1

I’m unable to test the code that runs on then of Promise

I have the following controller:

class Product extends Controller
  constructor: ($scope, productService) ->
    $scope.product = productService.new()
    $scope.products = []

    $scope.create = ->
      productService.create($scope.product).$promise.then (res) ->
        $scope.products.unshift(res)
        $scope.product = productService.new()

And the following test class:

describe 'productsController', ->
  q = scope = controller = productService = productServiceMock = undefined

beforeEach module('e-city')

beforeEach ->
  productServiceMock =
    new: -> a: 'a'
    create: (p)->
      qq = q.defer()
      qq.resolve(p)
      $promise: qq.promise
  module ($provide) ->
    $provide.value 'productService', productServiceMock
    null

beforeEach ->
  inject (_productService_, $controller, $rootScope, $q) ->
    q = $q
    productService = _productService_
    scope = $rootScope.$new()
    controller = $controller 'productController', $scope: scope

describe 'should test the create method', ->
  it 'should set a new object on $scope.product',  ->
    spy = sinon.spy productService, 'create'
    scope.create()
    spy.should.have.been.called

In my test I created a Mock to the productService to run the tests without disturbing the bank. The question of Mock is working properly, I just can’t test if productService.new() is being called when the Promise of productService.create($Scope.product) is solved. What could be?

1 answer

0


For this problem reported above in specific the code below already solves the problem.

describe 'create', ->
  it 'should call "new"', inject ($timeout)->
    spy = sinon.spy productService, 'new'
    scope.create()
    $timeout.flush()
    spy.should.have.been.called
    productService.new.restore()

Obs: To optimize the tests and facilitate the creation of mocks it is recommended to use the $httpBackend of Angularjs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.