Testing a function

Let's consider the following function, calculateBill. It takes totalHours and ratePerHours as the arguments, and returns the total bill:

const calculateBill = (totalHours, ratePerHours) => totalHours * ratePerHours;
module.exports = calculateBill;

To test, it let us create a file and call it calculateBill-test.js:

const calculateBill = require("../calculateBill");
test("calculate bills when the number of hours and the hourly rate is provided.", () => {
expect(calculateBill(10, 40)).toBe(400);
});

We can run the test by simply executing a yarn test command as:

yarn test
yarn run v1.12.1
$ jest
PASS app/JS/__tests__/calculateBill-test.js
calculate bills when the number of hours and hourly rate are provided. (4ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.62s

In this case, we intend to test our function calculateBill which is stored in the calculateBill.js file. We can run the test by executing yarn test command from the root folder of the project. 

To write the test, we used ES6 syntax and arrow function. The test statement is self-explanatory and quite readable. The statement says that when we call the function calculateBill with the arguments, 10 as the number of hours, and 40 as the hourly rate, the expected output is 400. Jest provides some handy functions that can be found at the official documentation site (https://jestjs.io/docs/en/using-matchers#truthiness), so that you can compare the results.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset