Unit Testing/Jest/Test Exceptions

From Wikiversity
Jump to navigation Jump to search

Create a JavaScript Program[edit | edit source]

Create the following JavaScript program. Save it as multiply.js

function multiply(x, y) {
    if (isNaN(x)) {
        throw new Error("x must be a number");
    }

    if (isNaN(y)) {
        throw new Error("y must be a number");
    }

    let result = x * y;
    return result;
}

module.exports = multiply;

Create a Test Program[edit | edit source]

Create the following Jest test program. Save it as multiply.test.js

const multiply = require("./multiply");

test("Multiply 2 * 2", () => {
    expect(multiply(2, 2)).toBe(4);
});

test("Multiply 2 * x", () => {
    expect(() => {
        multiply(2, "x");
    }).toThrow("y must be a number");    
});

Test Success[edit | edit source]

Test the program by running Jest in a terminal or command prompt in the same folder as the two programs above and observe the results.

npm test

Test Failure[edit | edit source]

Change the multiply source code somehow, such as removing the number validation. Test the program by running Jest again and observe the results.