2015-07-21 28 views
11

我正在使用Jasmine(2.2.0)間諜來查看是否調用某個回調。Jasmine間諜的重置呼叫不返回

測試代碼:

it('tests', function(done) { 
    var spy = jasmine.createSpy('mySpy'); 
    objectUnderTest.someFunction(spy).then(function() { 
    expect(spy).toHaveBeenCalled(); 
    done(); 
    }); 
}); 

可正常工作。但現在,我添加第二個層次:

it('tests deeper', function(done) { 
    var spy = jasmine.createSpy('mySpy'); 
    objectUnderTest.someFunction(spy).then(function() { 
    expect(spy).toHaveBeenCalled(); 
    spy.reset(); 
    return objectUnderTest.someFunction(spy); 
    }).then(function() { 
    expect(spy.toHaveBeenCalled()); 
    expect(spy.callCount).toBe(1); 
    done(); 
    }); 
}); 

這個測試不會返回,因爲顯然done回調永遠不會被調用。如果我刪除spy.reset()這一行,測試就完成了,但顯然在最後的期望中失敗了。但是,callCount字段似乎是undefined,而不是2

+0

它扔? –

+0

嘗試爲您的承諾添加拒絕處理程序。 – robertklep

+0

將'.catch(done)'添加到鏈的末尾,同樣的問題發生。所以@丹尼爾,如果它正在投擲,我無法檢測到它。 – Jorn

回答

22

關於間諜功能,Jasmine 2的語法與1.3不同。 見茉莉花文檔here

具體來說,你重置間諜與spy.calls.reset();

這是測試應該如何看起來像:

// Source 
var objectUnderTest = { 
    someFunction: function (cb) { 
     var promise = new Promise(function (resolve, reject) { 
      if (true) { 
       cb(); 
       resolve(); 
      } else { 
       reject(new Error("something bad happened")); 
      } 
     }); 
     return promise; 
    } 
} 

// Test 
describe('foo', function() { 
    it('tests', function (done) { 
     var spy = jasmine.createSpy('mySpy'); 
     objectUnderTest.someFunction(spy).then(function() { 
      expect(spy).toHaveBeenCalled(); 
      done(); 
     }); 
    }); 
    it('tests deeper', function (done) { 
     var spy = jasmine.createSpy('mySpy'); 
     objectUnderTest.someFunction(spy).then(function() { 
      expect(spy).toHaveBeenCalled(); 
      spy.calls.reset(); 
      return objectUnderTest.someFunction(spy); 
     }).then(function() { 
      expect(spy).toHaveBeenCalled(); 
      expect(spy.calls.count()).toBe(1); 
      done(); 
     }); 
    }); 
}); 

見小提琴here

+0

謝謝!顯然不是所有的文檔都更新爲新版本:( – Jorn

1

另一種方式來寫它:

spyOn(foo, 'bar'); 
expect(foo.bar).toHaveBeenCalled(); 
foo.bar.calls.reset();