我正在尝试为我的排序程序编写 Jasmine 单元测试.. 我是编写 Jasmine 和测试用例的新手.. 在下面提供我的代码... 你们能告诉我如何用 fiddle 来做吗...
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 );
} );
} );
你可以想出更多的测试用例。测试任何积极和消极的行为,并尝试考虑边缘情况。请记住,测试不仅是为了证明您的代码当前正常工作,也是为了确保它在未来的开发过程中不会中断。
可能的边缘情况:
- 应返回的数字是数组中的第一个或最后一个
- 数组中的
未定义
值(或NaN
、Infinity
……) - 具有相同绝对值的数字(例如
-0.01
和0.01
) - ...
关于javascript - 针对每个场景使用 Jasmine 的测试用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433701/