簡體   English   中英

如何為函數編寫單元測試?

[英]How to write unit test for a function?

我將單元測試帶到我的 javascript 文件中。 由於我不希望某些函數被繼承,所以我獨立聲明了一個函數。 如何編寫函數的單元測試? (就像下面的“getFormatData”)我還沒有找到關於這個的教程。 也許關鍵字不正確:) 我知道如何為 setValue 編寫 UT,但如何為“getFormatData”編寫 UT。我嘗試過但控制台顯示未定義 getFormat。 即使我添加了“window.getFormatData({});”,錯誤信息也是一樣的。

MockedObject.prototype.setValue(oData){
    var oMockedData = getFormatData(oData);

    this.setData(oMockedData);
};

function getFormatData(oData){
    return oData ? oData : 1;
}
//Test "setValue":

QUnit.module("Test setValue", funciton(assert){
    var control = new MockedObject()
    var oData = {};
    sinon.stub(window, "getFormatData").returns("MockedResult");
    sinon.stub(control, "setData");

    control.setValue(oData);

    assert.ok(control.setData.called, "setData is called");

    window.getFormatData.restore();
    control.setData.restore();
})

//Test "getFormatData": 
QUnit.module("getFormatData", function(assert) {
     // Act
     var result = getFormatData({});//var result = window.getFormatData({});

     //Assert
     assert.strictEqual(result, 1, "Accepted");
})

那么,getFormatData 有什么作用呢? 基於其輸入的預期結果是什么? 有兩種情況:oData為真--->返回oData; 或 oData 為假 ---> 1 返回;

在這種情況下,您可以調用例如getFormatData(113)並斷言返回值為 113,然后調用getFormatData(false)並斷言返回值是 1。getFormatData 上沒有更多要測試的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM