-
Notifications
You must be signed in to change notification settings - Fork 34
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.
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);
Next we can check if it's pretty much the same actual == expected
Expect("1").toEqual(1);
Expect(1 + 1).not.toEqual("3");
Now a cheeky little regular expression if you don't mind
Expect("something").toMatch(/some/);
Expect("another thing").not.toMatch(/something/);
Is it there or not? actual !== undefined
Expect("something").toBeDefined();
Expect(undefined).not.toBeDefined();
Is it something or not? actual === null
Expect(null).toBeNull();
Expect("something").not.toBeNull();
Is it trueish? actual == trueish
Expect(1).toBeTruthy();
Expect(0).not.toBeTruthy();
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);
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);
Which one's larger (hopefully the actual)
Expect(2).toBeGreaterThan(1);
Expect(1).not.toBeGreaterThan(2);
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);
Check whether a function throws an error
Expect(() => throw new Error()).toThrow();
Expect(() => {}).not.toThrow();
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");