angularjs - Jasmine 提示返回 Promise 的函数上出现 ".then is not a function"

标签 angularjs unit-testing asynchronous jasmine karma-jasmine

我正在测试一个函数,看看它是否正在调用一个返回 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/

相关文章:

javascript - 在select中设置选中项

c# - 如何异步运行 3 个进程,当一个返回期望值时停止其他两个并继续执行程序?

angularjs - 用户界面路由器 : How to validate parameter before state resolves

unit-testing - 如何创建 JUnit 4 测试套件以在抛出预期异常时通过

python - 在python 3.4中模拟内部对象的实例方法

unit-testing - 在 Android Studio Gutter 中启用代码覆盖率指示

javascript - 这是使现有 JavaScript 异步的方法吗?

javascript - 使用 setTimeout 推迟所有繁重的计算

javascript - 如何使用 AngularJS 向行添加单击和双击控件?

javascript - 将方法绑定(bind)到数组中的每个项目