In this section, will see how to add multiple tests and add multiple data sets to validate a function.
In functions.js file
const functions = {
add: (num1, num2) => {
if (typeof(num1) !== 'number' || typeof(num2) !== 'number'){
return null;
}
return num1 + num2;
}
};
module.exports=functions;
In functions.test.js file
const functions=require('./functions');
describe("Addition", () => {
it("should add two numbers ", () => {
expect(functions.add(2,2,)).toBe(4);
expect(functions.add(23,44,)).toBe(67);
expect(functions.add(15,20,)).not.toBe(25);
expect(functions.add(-5,5,)).toBe(0);
expect(functions.add(30,-10,)).toBe(20);
expect(functions.add(8,0,)).toBe(8);
});
it("should not add string ", () => {
expect(functions.add(2,"2",)).toBe(null);
expect(functions.add("-10",10,)).toBe(null);
});
it("should not add objects ", () => {
expect(functions.add(20,[],)).toBe(null);
});
it("should not add arrays ", () => {
expect(functions.add(5,{},)).toBe(null);
});
});
Results:
PASS ./functions.test.js
Addition
✓ should add two numbers (6ms)
✓ should not add string (1ms)
✓ should not add objects
✓ should not add arrays (1ms)
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 1.595s
Ran all test suites.