我正在测试一个函数,看看它是否正在调用一个返回 promise 的函数:
功能:
saveNew: (collection, query) ->
@newId
.then (id) ->
$http.post server + "/api/v1/saveJson/#{collection}/#{id}", query
newId 函数:
newId: () -> $http.get server + "/api/v1/newid"
测试:
describe "saveNew", () ->
it "should call to get a new id", () ->
spyOn(mySvc,"newId")
entitySvc.saveNew "myCollection", {data: "stuff"}
expect(entitySvc.newId).toHaveBeenCalled()
这会导致
TypeError: this.newId.then is not a function
同时,我测试了另一个调用返回 Promise 的函数的方法,并且它通过了:
findOne: (collection, query) -> @find collection, query
异步函数:
find: (collection, query) ->
$http.post server + "/api/v1/findJson/#{collection}", query
测试:
describe "#findOne", () ->
it "should call #find", () ->
query = {id:1}
collection = "myCollection"
spyOn(mySvc,"find")
mySvc.findOne collection, query
expect(mySvc.find).toHaveBeenCalledWith(collection,query)
最佳答案
您可以通过假电话进行监视。这允许您通过 Promise 返回您想要的数据。
spyOn(mySvc, 'newId').andCallFake(function () {
return $.Deferred().resolve(1);
});
然后您可以验证返回的 newId 是否是您所期望的
关于angularjs - Jasmine 提示返回 Promise 的函数上出现 ".then is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655195/