单元测试:
describe "Lunch controller", ->
beforeEach module('Lunch')
beforeEach inject(($httpBackend) ->
$httpBackend.expectGET('/lunchers')
.respond(200, ["some content", "some other content"])
)
describe "LunchCtrl", ->
it "should set images to a populated array", inject(($controller, $httpBackend) ->
scope = {}
ctrl = $controller("LunchPoolController",
$scope: scope
)
expect(scope.lunchers.length).toBe 2
)
扔
at /Users/jd/Dropbox/apps/lookingtolunch/spec/javascripts/controller_specs.js.coffee:13
INFO [watcher]: Changed file "/Users/jd/Dropbox/apps/lookingtolunch/spec/javascripts/controller_specs.js.coffee".
Chrome 32.0.1700 (Mac OS X 10.9.1) Lunch controller LunchCtrl should set images to a populated array FAILED
TypeError: Cannot read property 'length' of undefined
at null.<anonymous> (/Users/jd/Dropbox/apps/lookingtolunch/spec/javascripts/controller_specs.js.js:13:35)
at Object.invoke (http://localhost:3000/assets/application.js:7886:19)
at workFn (http://localhost:3000/assets/application.js:14982:22)
Error: Declaration Location
at window.inject.angular.mock.inject (http://localhost:3000/assets/application.js:14970:27)
at null.<anonymous> (/Users/jd/Dropbox/apps/lookingtolunch/spec/javascripts/controller_specs.js.js:7:57)
at null.<anonymous> (/Users/jd/Dropbox/apps/lookingtolunch/spec/javascripts/controller_specs.js.js:6:10)
at /Users/jd/Dropbox/apps/lookingtolunch/spec/javascripts/controller_specs.js.js:1:1
Chrome 32.0.1700 (Mac OS X 10.9.1): Executed 2 of 2 (1 FAILED) (2.766 secs / 0.201 secs)
最佳答案
假设LunchPoolController
正在触发HTTP请求,则需要使用$httpBackend.flush()
来确保所有请求都通过。 (有关更多信息,请参见Flushing HTTP requests部分)。
关于javascript - 我在正确 mock httpBackend吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21567502/