settingsAccountsettings
Menusettings

Q: Even or Odd (unit testing task with Mocha and Chai)

+2 votes

You need to write unit tests for a function isOddOrEven that checks whether a passed in string has even or odd length. The function has the following functionality:

  • isOddOrEven(string) - A function that accepts a string and determines if the string has even or odd length.
    • If the passed parameter is not a string return undefined.
    • If the parameter is a string - return either "even" or "odd" based on the string's length.

JS Code

To ease you in the process, you are provided with an implementation which meets all of the specification requirements for the isOddOrEven function:

function isOddOrEven(string) {
    if (typeof(string) !== 'string') {
        return undefined;
    }
    if (string.length % 2 === 0) {
        return "even";
    }
    return "odd";
}

//console.log(isOddOrEven("opar"));
console.log(isOddOrEven("opa").length);

module.exports = {isOddOrEven};//for the file from which we import

Your tests will be supplied a function named "isOddOrEven" which contains the above mentioned logic, all test cases you write should reference this function. You can check the example at the beginning of this document to grasp the syntax.

asked in JavaScript category by user mitko

1 Answer

+2 votes

My Mocha and Chai tests:

let isOddOrEven = require("../02.EvenOrOdd").isOddOrEven;
let expect = require("chai").expect;

describe("Tests for this task", function () {

    describe("Function tests - checks if the it is string", function () {
        it("should be a string", function () {
            expect(typeof isOddOrEven("32")).to.equal("string");
        });

        it("should be a undefined if not a string", function () {
            expect(isOddOrEven(1)).to.be.undefined;
        });
    });

    describe("Check the length of the string", function () {
        it("should be even", function () {
            expect(isOddOrEven("32")).to.equal("even");
        });

        it("should be odd", function () {
            expect(isOddOrEven("323")).to.equal("odd");
        });
    });
});

Explanation:

We can clearly see there are 3 outcomes of the function:

  • Returning undefined.
  • Returning "even".
  • Returning "odd".

We can write one or two tests passing things other than string to the function and expecting it to return undefined.

After we've checked the validation it's time to check whether the function works correctly with proper arguments. We can write a test for each of the cases. One where we pass a string with even length. And one where we pass a string with an odd length.

Finally we can make an extra test passing multiple different strings in a row to ensure the function is consistent.

 

answered by user ak47seo
Thanks! Nice and helpful explanations!
...