test cases using Jasmine for each scenario

2.7k views Asked by At

I am trying to write a jasmine unit test for my sorted programme.. i am new in writing jasmine as well as test case.. providing my code an-below below... can you guys tell me how to do it in a 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));
1

There are 1 answers

1
Ingo Bürk On

Example test cases could look like this

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

You can think of more test cases. Test any positive and negative behavior and try to think of edge cases. Keep in mind that tests are not just to prove your code is currently working, but also to ensure that it doesn't break during future development.

Possible edge cases:

  • the number that should be returned is the first or last in the array
  • undefined values in the array (or NaN, Infinity, …)
  • numbers with identical absolute values (e.g. -0.01 and 0.01)