2017-07-25 67 views
3

我在用sinon和chai編寫javascript測試時遇到問題。 我想檢查是否一個函數被調用的間諜,並得到「錯誤:無效的柴屬性:calledOnce」當調用calledOnce時無效Chai屬性

我做在同一個測試依賴另一個項目同樣的事情,沒有任何問題...

var udpSocketStub = this.sandbox.spy(udpSocket, 'send'); 
expect(udpSocketStub).calledOnce; // SHOULD FAIL 


"dependencies": { 
    "body-parser": "~1.17.1", 
    "bootstrap": "^4.0.0-alpha.6", 
    "chai": "^4.1.0", 
    "co-mocha": "^1.2.0", 
    "cookie-parser": "~1.4.3", 
    "debug": "~2.6.3", 
    "express": "~4.15.2", 
    "jquery": "^3.2.1", 
    "mocha": "^3.4.2", 
    "morgan": "~1.8.1", 
    "node-compass": "0.2.3", 
    "pug": "^2.0.0-rc.1", 
    "serve-favicon": "~2.4.2", 
    "sinon": "^2.3.8", 
    "sinon-chai": "^2.12.0" 
} 
+1

你確定嗎?我認爲它應該是'expect(udpSocketStub.send.calledOnce).to.be.true',如果我錯了,請糾正我。 – hinok

+0

@hinok http://ricostacruz.com/cheatsheets/sinon-chai.html看起來你不需要'to.be.true'。 –

+0

@Elliott sinon-chai,我錯過了這個套餐,你說得對。但仍然可能它應該是'expect(udpSocketStub.send).calledOnce;' – hinok

回答

5

你只是缺少sinon-chai包,增加了興農般的斷言柴。

npm install --save sinon-chai 

初始化:

var chai = require('chai'); 
var sinon = require('sinon'); 
chai.use(require('sinon-chai')); 

如果你想知道,使用存根或原有功能都工作:

var expect = chai.expect; 

var udpSocketStub = this.sandbox.spy(udpSocket, 'send'); 

// Make a call 
updSocket.send({..}); 

// Both should pass 
expect(udpSocketStub).calledOnce; 
expect(udpSocket.send).calledOnce; 

// Identical, but more readable 
expect(udpSocketStub).to.have.been.calledOnce; 
expect(udpSocket.send).to.have.been.calledOnce; 
+0

感謝您的回答,因爲這解決了我的問題...您是否介意解釋或指向我回答如何執行'chai.use (require('sinon-chai'));'如果你正在嘗試執行'import'而不是'require',那麼這行呢? – levininja

+1

你可以嘗試從'sinon-chai''導入sinonChai,然後'chai.use(sinonChai)',但是你使用的是TypeScript,我是對嗎?我不確定sinon-chai是否支持打字稿。 – Overdrivr

+0

如果您覺得我解決了您的問題,請隨時選中綠色箭頭標記爲已回答的問題;) – Overdrivr