使用 AngularJS、CoffeeScript 和 Jasmine(在 WebStorm 中编辑),我想对一系列承诺进行单元测试。
假设我有以下示例服务:
角度服务
class ExampleService
stepData: []
constructor: (@$http) ->
attachScopeMethod: (@scope) ->
@scope.callSteps = => @step1().then -> @step2()
step1: ->
@$http.get('app/step/1').then (results) =>
@stepData[0] = results.data
results
step2: ->
@$http.get('app/step/2').then (results) =>
@stepData[2] = results.data
results
该服务允许我附加一个方法callSteps()
到范围。调用此方法时,会对第 3 方 API 执行一系列异步 $http 调用。
为了测试每个步骤是否至少被调用,我编写了以下 Jasmine 规范。
茉莉花规格
ddescribe 'ExampleService', ->
beforeEach ->
module 'myApp'
beforeEach inject ($rootScope, $injector) ->
@scope = $rootScope.$new()
@exampleService = $injector.get 'exampleService'
@q = $injector.get '$q'
describe 'process example steps', ->
beforeEach ->
@exampleService.attachScopeMethod(@scope)
it "should attach the scope method", ->
expect(@scope.callSteps).toBeDefined()
describe 'when called should invoke the promise chain', ->
it "should call step1 and step2", ->
defer = @q.defer()
@exampleService.step1 = jasmine.createSpy('step1').andReturn(defer.promise)
@exampleService.step2 = jasmine.createSpy('step2')
@scope.callSteps()
defer.resolve()
expect(@exampleService.step1).toHaveBeenCalled()
expect(@exampleService.step2).toHaveBeenCalled()
本次测试结果如下:
- 期望(@exampleService.step1).toHaveBeenCalled() -PASS
- 期望(@exampleService.step2).toHaveBeenCalled() -FAIL
你能告诉我怎样才能得到step2()
测试成功运行?
谢谢
EDIT
下面的@Dashu 友善地提供了问题的答案。诀窍是简单地调用scope.$apply
or scope.$digest
触发承诺链决议。
这是工作测试片段。
describe 'when called should invoke the promise chain', ->
it "should call step1 and step2", ->
defer = @q.defer()
defer.resolve()
@exampleService.step1 = jasmine.createSpy('step1').andReturn(defer.promise)
@exampleService.step2 = jasmine.createSpy('step2')
@scope.callSteps()
@scope.$apply()
expect(@exampleService.step1).toHaveBeenCalled()
expect(@exampleService.step2).toHaveBeenCalled()