Injecting dependent services when unit testing AngularJS services

后端 未结 5 1494
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 00:06

I\'m testing service A, but service A depends on service B (i.e. service B is injected into service A).

I\'ve seen this question but my case is a bit different becau

5条回答
  •  清歌不尽
    2020-12-08 00:59

    I was doing this in CoffeeScript and found an extra gotcha. (Also, I found the code on this page to be confusingly terse.) Here's a complete working example:

    describe 'serviceA', ->
       mockServiceB = {}
    
       beforeEach module 'myApp' # (or just 'myApp.services')
    
       beforeEach ->
          angular.mock.module ($provide) ->
             $provide.value 'serviceB', mockServiceB
             null
    
       serviceA = null
       beforeEach inject ($injector) ->
          serviceA = $injector.get 'serviceA'
    
       it 'should work', ->
          expect( true ).toBe( true )
          #serviceA.doStuff()
    

    Without explicitly returning null after $provide.value, I kept getting Error: Argument 'fn' is not a function, got Object. I found the answer in this Google Groups thread.

提交回复
热议问题