Skip to content

Matchers

James Adarich edited this page Jul 6, 2018 · 8 revisions

Now you've set up some tests, it's time to check your code is working. Let's start easy.

toBe

To be or not to be, that is the question! Simply put this checks whether actual === expected

Expect(1 + 1).toBe(2);
Expect(1 + 1).not.toBe(3);

toEqual

Next we can check if it's pretty much the same actual == expected

Expect("1").toEqual(1);
Expect(1 + 1).not.toEqual("3");

toMatch

Now a cheeky little regular expression if you don't mind

Expect("something").toMatch(/some/);
Expect("another thing").not.toMatch(/something/);

toBeDefined

Is it there or not? actual !== undefined

Expect("something").toBeDefined();
Expect(undefined).not.toBeDefined();

toBeNull

Is it something or not? actual === null

Expect(null).toBeNull();
Expect("something").not.toBeNull();

toBeTruthy

Is it trueish? actual == trueish

Expect(1).toBeTruthy();
Expect(0).not.toBeTruthy();

toContain

Does the string contain another string or an array contain an item?

Expect("something").toContain("thing");
Expect([1, 2, 3]).toContain(2);
Expect("another thing").not.toContain("something");
Expect([1, 2, 3]).not.toContain(4);

toBeEmpty

Is an array, string or object empty?

Expect([]).toBeEmpty();
Expect("").toBeEmpty();
Expect({}).toBeEmpty();
Expect([ "some", "items" ]).not.toBeEmpty();
Expect("something").not.toBeEmpty();
Expect({ a: "property" }).not.toBeEmpty();

toBeGreaterThan

Which one's larger (hopefully the actual)

Expect(2).toBeGreaterThan(1);
Expect(1).not.toBeGreaterThan(2);

toBeLessThan

For when you don't want things to get out of control, check it's not too big

Expect(1).toBeLessThan(2);
Expect(2).not.toBeLessThan(1);

toThrow

Check whether a function throws an error

Expect(funct).toThrow();
Expect(func).not.toThrow();

// note async checks must be awaited
await Expect(asyncFunc).toThrowAsync();
await Expect(asyncFunc).not.toThrowAsync();

toThrowError

Check whether a function throws a specific error with a given message

Expect(func).toThrowError(TypeError, "things went wrong");
Expect(func).not.toThrowError(TypeError, "super nasty error");

// note async checks must be awaited
await Expect(asyncFunc).toThrowErrorAsync(TypeError, "things went wrong");
await Expect(asyncFunc).not.toThrowErrorAsync(TypeError, "super nasty error");
Clone this wiki locally