Skip to content

Instantly share code, notes, and snippets.

@RanjanSushant
Created January 29, 2022 08:01
Show Gist options
  • Save RanjanSushant/d15d9b95d0b8b9fc49e9b21994e4f9c6 to your computer and use it in GitHub Desktop.
Save RanjanSushant/d15d9b95d0b8b9fc49e9b21994e4f9c6 to your computer and use it in GitHub Desktop.
Codesphere Jest demo intro to matchers
//function to add
const add = (num1, num2) => num1 + num2;
//function to multiply
const multiply = (num1, num2) => num1 * num2;
//function to create an Object
const createUser = () => {
const user = {
firstName: "Luke",
lastName: "Skywalker",
};
return user;
};
//exporting
module.exports = { add, multiply, createUser };
//importing my file to be tested
const func = require("./functions");
//testing the add function using toBe matcher
test("adds 2 and 2 to give 4", () => {
expect(func.add(2, 2)).toBe(4);
});
//testing the multiply function using toBe matcher
test("multiplies 12 and 13 to give 156", () => {
expect(func.multiply(12, 13)).toBe(156);
});
//using the toBeLessThanOrEqual matcher
test("Should be under 25", () => {
const weight = 70;
const height = 180 / 100;
const bmi = weight / (height * height);
expect(bmi).toBeLessThanOrEqual(25);
});
//using the toBeCloseTo matcher for floats
test("Floating point numbers", () => {
const value = 1.3 + 2.9;
expect(value).toBeCloseTo(4.2);
});
//using the toMatch matcher for regex
test("Secret Ingredient", () => {
expect("There is no secret ingredient").toMatch(/secret/);
});
//using the toEqual matcher for Object type
test("Luke Skywalker", () => {
expect(func.createUser()).toEqual({
firstName: "Luke",
lastName: "Skywalker",
});
});
//using the toContain matcher for specific element in array
test("Master Oogway", () => {
const hisWords = ["There", "are", "no", "accidents"];
expect(hisWords).toContain("accidents");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment