2016-11-21 66 views
0

我試圖使用sinon.spy()來檢查函數是否已被調用。該函數被稱爲getMarketLabel,它返回marketLabel並將其接受到函數中。我需要檢查getMarketLabel已被調用。我實際調用getMarketLabel在一個地方,像這樣: {getMarketLabel(sel.get('market'))} 我到目前爲止的代碼是:Sinon Spy檢查函數被稱爲

describe('Check if it has been called',() => { 
    let spy; 
    beforeEach(() => { 
    spy = sinon.spy(getMarketLabel, 'marketLabel'); 
    }) 
    it('should have been called',() => { 
    expect(spy).to.be.calledWith('marketLabel'); 
    }); 
}); 

這是錯誤我收到: TypeError: Attempted to wrap undefined property marketLabel as function

回答

1

興農無法窺視功能,那不是某個對象的屬性,因爲Sinon必須能夠用該函數的窺視版本替換原始功能getMarketLabel

工作的示例:

let obj = { 
    getMarketLabel(label) { 
    ... 
    } 
} 
sinon.spy(obj, 'getMarketLabel'); 

// This would call the spy: 
obj.getMarketLabel(...); 

這個語法(這是接近你所使用的)也存在:

let spy = sinon.spy(getMarketLabel); 

然而,這只是觸發間諜代碼顯式調用spy()當;當您直接撥打getMarketLabel()時,根本不會調用間諜代碼。

而且,這也不行:

let getMarketLabel = (...) => { ... } 
let obj   = { getMarketLabel } 
sinon.spy(obj, 'getMarketLabel'); 

getMarketLabel(...); 

因爲你還是直接調用getMarketLabel

+0

請參見本文的jsfiddle:https://jsfiddle.net/hv8mLwcL/ – DaveDavidson

+0

@DaveDavidson'sinon.spy(getMarketLabel, 'marketLabel' )'無效:'getMarketLabel'不是一個對象,'marketLabel'不是一個函數。 – robertklep

0

這是錯誤我收到:TypeError: Attempted to wrap undefined property marketLabel as function

您需要要求helper.js到您的測試文件,然後替換相關的方法所需要的模塊,最後調用與替代方法諜照:

var myModule = require('helpers'); // make sure to specify the right path to the file 

describe('HistorySelection component',() => { 
    let spy; 
    beforeEach(() => { 
    spy = sinon.stub(myModule, 'getMarketLabel'); // replaces method on myModule with spy 
    }) 
    it('blah',() => { 
    myModule.getMarketLabel('input'); 
    expect(spy).to.be.calledWith('input'); 
    }); 
}); 

您不能測試諜是否被調用helpers.sel('marketLabel')如進行測試之前,該功能將被執行。因此,您可以通過書面形式將:

expect(spy).to.be.calledWith(helpers.sel('marketLabel'));

被測試的是該間諜被稱爲與helpers.sel('marketLabel')返回任何值(這是undefined默認情況下)。


helper.js的內容應該是:

module.exports = { 
    getMarketLabel: function (marketLabel) { 
    return marketLabel 
    } 
} 
+0

雖然我不確定應該在助手文件中。目前這是我的:https://jsfiddle.net/8q1tLhs7/ 而且我仍然收到相同的錯誤。 – DaveDavidson

+0

@DaveDavidson:查看更新的答案。不確定你爲什麼做一個無效語法的'return {getMarketLabel}'。我將它改爲'return marketLabel'。 – rabbitco

+0

這不適合我。我仍然得到同樣的錯誤。 – DaveDavidson