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

标签 javascript unit-testing jasmine testcase jasmine-jquery

我正在尝试为我的排序程序编写 Jasmine 单元测试.. 我是编写 Jasmine 和测试用例的新手.. 在下面提供我的代码... 你们能告诉我如何用 fiddle 来做吗...

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

你可以想出更多的测试用例。测试任何积极和消极的行为,并尝试考虑边缘情况。请记住,测试不仅是为了证明您的代码当前正常工作,也是为了确保它在未来的开发过程中不会中断。

可能的边缘情况:

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

关于javascript - 针对每个场景使用 Jasmine 的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433701/

相关文章:

javascript - 您如何获得对模块中定义的 angularjs Controller 的引用?

javascript - 如何在 PortalScript (ECMAScript5) 中导出单元测试函数

AngularJS - 单元测试 - 使用同一服务的模拟中的原始服务?

javascript - 如何快速清除 JavaScript 对象?

c# - 用于测试 Mono 的隔离框架

javascript - parent 和 child 的触摸事件分开

c# - C# 单元测试中未启用 ILogger.LogLevel

c# - 通用类无法匹配参数列表

javascript - JavaScript 中的随机对象

javascript - 使用 Fetch API 读取响应 header