【问题标题】:test cases using Jasmine for each scenario为每个场景使用 Jasmine 的测试用例
【发布时间】:2013-12-24 09:11:23
【问题描述】:

我正在尝试为我的排序程序编写一个 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));

【问题讨论】:

  • 你的函数更高效的版本是:function getClosestToZero(numberSet){ var current, i = 0, l = numberSet.length, min = Number.POSITIVE_INFINITY, min_abs = Number.POSITIVE_INFINITY; for ( ; i&lt;l; ++i ) { current = Math.abs( numberSet[i] ); if ( current &lt; min_abs ) { min = numberSet[i]; min_abs = current; } } return min; }

标签: javascript unit-testing jasmine testcase jasmine-jquery


【解决方案1】:

示例测试用例可能如下所示

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

【讨论】:

  • 如果你知道 Jasmine 是什么,你就不必问了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-30
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多