针对每个场景使用Jasmine测试用例

test cases using Jasmine for each scenario

本文关键字:Jasmine 测试用例      更新时间:2024-04-05

我正试图为我的排序程序编写一个jasmine单元测试。。我刚开始写茉莉花和测试用例。。在下面提供我的代码。。。你们能告诉我怎么用小提琴演奏吗。。。

http://jsfiddle.net/YYg8U/

var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];
function getClosestToZero(numberSet) {
    var i = 0, positiveSet = [], positiveClosest = 0;
    for (i = 0; i < numberSet.length; i += 1) {
        positiveSet.push(numberSet[i] >= 0 ? numberSet[i] : numberSet[i] * -1);
    }
    positiveClosest = Math.min.apply(Math, positiveSet);
    return numberSet[positiveSet.indexOf(positiveClosest)];
}
alert(getClosestToZero(myNumbersToSort));

示例测试用例可能看起来像这个

describe( 'getClosestToZero', function () {
    it( 'finds a positive unique number near zero', function () {
        expect( getClosestToZero( [-1, 0.5, 0.01, 3, -0.2] ) ).toBe( 0.01 );
    } );
    it( 'finds a negative unique number near zero', function () {
        expect( getClosestToZero( [-1, 0.5, -0.01, 3, -0.2] ) ).toBe( -0.01 );
    } );
    // your method actually doesn't pass this test
    // think about what your method *should* do here and if needed, fix it
    it( 'finds one of multiple identical numbers near zero', function () {
        expect( getClosestToZero( [-1, 0.5, 0.01, 0.01, 3, -0.2] ) ).toBe( 0.01 );
    } );
} );

你可以考虑更多的测试用例。测试任何积极和消极的行为,并尝试思考边缘案例。请记住,测试不仅是为了证明您的代码目前正在运行,而且是为了确保它在未来的开发过程中不会中断。

可能的边缘情况:

  • 应该返回的数字是数组中的第一个或最后一个
  • 数组中的undefined值(或NaNInfinity…)
  • 具有相同绝对值的数字(例如-0.010.01