-
Notifications
You must be signed in to change notification settings - Fork 34
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.
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([]).toBeEmpty();
Expect("").toBeEmpty();
Expect({}).toBeEmpty();
Expect([ "some", "items" ]).not.toBeEmpty();
Expect("something").not.toBeEmpty();
Expect({ a: "property" }).not.toBeEmpty();
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(funct).toThrow();
Expect(func).not.toThrow();
// note async checks must be awaited
await Expect(asyncFunc).toThrowAsync();
await Expect(asyncFunc).not.toThrowAsync();
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");