Basic unit testing with Jest

Posted on

in

Let’s say for example we have a back end function that checks if you are under age from a user’s date of birth. First we load that function:

const {validateAge} = require("../linkToFile");

Then we set up some test data, like so:

const youngYear = new Date().getFullYear() - 17;
const oldYear = new Date().getFullYear() - 19;

const testDataUnderage = {
 dateOfBirth: youngYear + "-06-06";
}

const testDataOld = {
 dateOfBirth: oldYear + "-06-06";
}

We then run the function using the test datas. In our example the function will return some validation error text that will display in a popup if there are any validation errors and will return nothing if you are not underaged.

test("test validateAge", async () => {
 const resultUnderage = await validateAge(testDataUnderage);
 expect(resultUnderage[0].title).toEqual("Sorry, you are underaged.");
 const resultOld = await validateAge(testDataOld);
 expect(resultOld[0].toEqual(undefined);
}

We give the test a name (in this case “test validateAge”), we pass it test data and then tell it the result we expect. If it fails then something caused the code to no longer work.

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930