简体   繁体   中英

How to write unit test for a function?

I'm bringing unit tests to my javascript files. Since I don't want some functions to be inherited, so I declare a function independently. How can I write the function's unit test? (Like "getFormatData" below) I haven't found a tutorial about this. Maybe the keywords are incorrect :) I know how to write UT for setValue, but how to write UT for "getFormatData".I tried but console show that getFormat is not defined. Even I add "window.getFormatData({});", the error message is same.

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");
})

Well, what does getFormatData do? What are the expected results based on its input? There are two cases: oData is truthy ---> oData is returned; or oData is falsy ---> 1 is returned;

In this case, you could call for example getFormatData(113) and assert that the return value is 113, then call getFormatData(false) and assert that the return value is 1. There is not much more to test on getFormatData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM