Jest sounds like a name of a mean girl. But she's just expecting something good.
Here's Jest's Life Journey
The reference doc : jestjs.io
class Masterpiece {}
const dreamDress = { dress: 'red gown', shoes: 'heels', accessories: ['necklace', 'bracelet'] };
const genuineSoul = { name: 'Maya', traits: ['loyal', 'funny'] };
const imposterSoul = { name: 'Maya', traits: ['loyal', 'funny'] };
describe("Jest's Life Journey — A Matcher Story", () => {
// I. General Equality & Truthiness
test('Jest knows what she wants in love and life', () => {
const oneTrueLove = 'Alex';
const backup = 'Alex';
expect(oneTrueLove).toBe('Alex'); // toBe
expect(dreamDress).toEqual({ dress: 'red gown', shoes: 'heels', accessories: ['necklace', 'bracelet'] }); // toEqual
expect(genuineSoul).toStrictEqual({ name: 'Maya', traits: ['loyal', 'funny'] }); // toStrictEqual
const weekendPlans = 'Spa Day';
let worries = undefined;
const sharedGossip = null;
expect(weekendPlans).toBeDefined(); // toBeDefined
expect(worries).toBeUndefined(); // toBeUndefined
expect(sharedGossip).toBeNull(); // toBeNull
const dedication = true;
const selfDoubt = 0;
expect(dedication).toBeTruthy(); // toBeTruthy
expect(selfDoubt).toBeFalsy(); // toBeFalsy
});
// II. Number Matchers
test('Jest evaluates her stats', () => {
const jumpShot = 9.9999;
const complimentsToday = 5;
const dailyDrama = 1;
const nonsense = 0 / 0;
expect(jumpShot).toBeCloseTo(10, 3); // toBeCloseTo
expect(complimentsToday).toBeGreaterThan(3); // toBeGreaterThan
expect(dailyDrama).toBeLessThanOrEqual(1); // toBeLessThanOrEqual
expect(nonsense).toBeNaN(); // toBeNaN
});
// III. String Matchers
test('Jest decodes whispers', () => {
const whisper = "I think they're planning a secret plans party";
expect(whisper).toMatch(/secret plans/); // toMatch
});
// IV. Arrays & Iterables
test('Jest organizes her life essentials', () => {
const backpack = ['laptop', 'notebook', 'favorite book'];
const marbles = [{ color: 'blue', pattern: 'swirl' }, { color: 'green' }];
const wishList = ['bike', 'camera', 'trip', 'skates', 'journal'];
expect(backpack).toContain('favorite book'); // toContain
expect(marbles).toContainEqual({ color: 'blue', pattern: 'swirl' }); // toContainEqual
expect(wishList).toHaveLength(5); // toHaveLength
});
// V. Objects & Class Matchers
test('Jest evaluates structure and essence', () => {
const dreamJob = {
title: 'Creative Director',
benefits: {
healthInsurance: true,
gym: true
}
};
const newFriend = {
personality: 'kind',
hobbies: ['reading', 'hiking', 'gaming']
};
const art = new Masterpiece();
expect(dreamJob).toHaveProperty('benefits.healthInsurance'); // toHaveProperty
expect(newFriend).toMatchObject({ personality: 'kind', hobbies: ['reading', 'hiking'] }); // toMatchObject
expect(art).toBeInstanceOf(Masterpiece); // toBeInstanceOf
});
// VI. Mock Functions & Spies
test('Jest observes the world around her', () => {
const phoneCall = jest.fn();
phoneCall();
expect(phoneCall).toHaveBeenCalled(); // toHaveBeenCalled
const momCalls = jest.fn();
momCalls();
momCalls();
expect(momCalls).toHaveBeenCalledTimes(2); // toHaveBeenCalledTimes
const delivery = jest.fn();
delivery('pizza', 'extra cheese', 'on time');
expect(delivery).toHaveBeenCalledWith('pizza', 'extra cheese', 'on time'); // toHaveBeenCalledWith
expect(delivery).toHaveBeenLastCalledWith('pizza', 'extra cheese', 'on time'); // toHaveBeenLastCalledWith
const advice = jest.fn(() => 'solution');
advice();
expect(advice).toHaveReturned(); // toHaveReturned
expect(advice).toHaveReturnedWith('solution'); // toHaveReturnedWith
});
// VII. Exception Handling
test('Jest knows when things go splash', () => {
function juggleWaterBalloons() {
throw new Error("SplashError: Everything is wet!");
}
expect(juggleWaterBalloons).toThrow("SplashError: Everything is wet!"); // toThrow
});
// VIII. Async Matchers
test('Jest is patient and hopeful', async () => {
const dream = Promise.resolve('a reality!');
const toughProblem = Promise.reject(new Error("TooHardError: Give up!"));
await expect(dream).resolves.toBe('a reality!'); // resolves.toBe
await expect(toughProblem).rejects.toThrow('TooHardError: Give up!'); // rejects.toThrow
});
// IX. Snapshot Matchers
test('Jest remembers everything', () => {
const currentRoom = {
bed: 'made',
desk: 'organized',
lights: 'fairy lights'
};
expect(currentRoom).toMatchSnapshot(); // toMatchSnapshot
const currentMood = 'fabulous!';
expect(currentMood).toMatchInlineSnapshot(`'fabulous!'`); // toMatchInlineSnapshot
});
// X. Assertion Counts
test('Jest double checks everything', () => {
expect.assertions(3); // assertions
expect('backpack packed').toBeDefined();
expect('lunch ready').toBeDefined();
expect('shoes tied').toBeDefined();
});
test('At least one thing checked', () => {
expect.hasAssertions(); // hasAssertions
expect('door locked').toBeDefined();
});
// XI. Modifiers
test("Jest knows what's *not* right", () => {
const littleBrotherRoom = 'messy';
expect(littleBrotherRoom).not.toBe('clean'); // not.toBe
});
// XII. Asymmetric Matchers
test('Jest is flexible when needed', () => {
expect({ wrapping: 'polka dots' }).toEqual({ wrapping: expect.anything() }); // expect.anything
expect(42).toBe(expect.any(Number)); // expect.any(Constructor)
expect(['chocolate', 'chips', 'nuts']).toEqual(expect.arrayContaining(['chocolate', 'chips'])); // arrayContaining
expect({ happy: true, successful: true, rich: false }).toMatchObject(
expect.objectContaining({ happy: true, successful: true })
); // objectContaining
expect("This is a joyful tune.").toMatch(expect.stringContaining('joyful')); // stringContaining
expect(['mow lawn', 'walk dog']).not.toEqual(expect.arrayContaining(['dishes', 'laundry'])); // not.arrayContaining
});
// XIII. Custom Matchers
expect.extend({
toHaveSparkle(received) {
const pass = received.includes('✨');
if (pass) {
return {
message: () => `expected ${received} not to sparkle`,
pass: true
};
} else {
return {
message: () => `expected ${received} to have sparkle ✨`,
pass: false
};
}
}
});
test('Jest makes her own rules', () => {
expect('These shoes are ✨ amazing!').toHaveSparkle(); // custom matcher
});
});
Top comments (0)