注意:我正在用 CoffeeScript 编写所有内容
我有一个 Controller 如下:
angular.module('myApp').controller 'MyController', ($scope, $routeParams, Batch) ->
$scope.$on '$routeChangeSuccess', () ->
Batch.get {batchUuid: $routeParams.batchUuid}, (response) ->
$scope.batch_id = response.id
controller拉取Batch资源,定义如下:
angular.module('myApp').factory 'Batch', ($resource) ->
$resource '/batches/:batchUuid', {}
我有如下路线:
$routeProvider.when('/batches/:batchUuid',
{ templateUrl: 'batches-processing.html', controller: 'MyController' })
所以:
- 您访问路线/batches/22
- 它使用 MyController
- 它触发$routeChangeSuccess
- 它从路由中调用 batchUuid 获取 Batch 资源
- 它返回一个 json 响应并将一个 id 分配给 $scope.batch_id
现在我想测试这个,所以我有一个单元测试如下:
describe 'Controllers', ->
beforeEach module 'myApp'
describe 'MyController', ->
scope = {}
ctrl= {}
beforeEach inject ($rootScope, $controller, Batch, $httpBackend) ->
scope = $rootScope.$new()
ctrl = $controller('MyController', ($scope: scope))
#I imagine I need to use either my injected Batch resource or the httpBackend to fake/expect the ajax call here
it "Gets data from the resource and assigns it to scope", () ->
#How on earth do I test this
我见过有人使用 $httpBackend.expect('/endpoint.json').respond({id:1}) 等,但我不能那样做。我的资源 URL 依赖于路由中的 batchUuid。我如何模拟/伪造/实现将模拟路由更改、触发 $routeChangeSuccess、将 routeParameter 传递给资源、获取资源并测试结果的测试?
我在这上面扯了扯头发,但 Angular 文档似乎没有涵盖它。
谢谢!
最佳答案
你可以制作一个假的 routeParams 并将其注入(inject)到你的 Controller 中。
我使用 jasmine 的 createSpy 来伪装,但这可能有点矫枉过正。有一个例子 here这展示了如何创建和注入(inject)假的 routeParams。
关于javascript - 使用 $routeParams 资源对 AngularJS Controller 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13304083/