Skip to content

Matchers

James Richford edited this page Jan 26, 2017 · 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("something").toContain("thing");
Expect([1, 2, 3]).toContain(2);
Expect("another thing").not.toContain("something");
Expect([1, 2, 3]).not.toContain(4);

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(() => throw new Error()).toThrow();
Expect(() => {}).not.toThrow();

toThrowError

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

Expect(() => throw new TypeError("things went wrong")).toThrowError(TypeError, "things went wrong");
Expect(() => throw new Error("some error we don't care about")).not.toThrowError(TypeError, "super nasty error");
Clone this wiki locally