1. What is jest
Jest is produced by facebook as a code testing frame. It has implemented with functions of Mocha,chai,jsdomandsinon, and you can know more about jest through Starter and GitHub.
2. How to start
After installed jest:
npm install --save-dev jest
And run npm run jest, then jest will print messages as:
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)
Jest by default it will auto to check all the file in your project which contains the suffix as .test.js or .spect.js(also .ts). More config can be seen and set in the package.json file. For example:
{
"scripts": {
"test": "jest" //npm run test
},
"jset": {
"testRegex": "/test/.*.spec.ts$" //following the rules of regular matching
}
}
Jest only try to run test in the files in tess folder with .spec.ts suffix.
3. How to use
The core function of jest is the Mathcers.
expect(funciton()).matchers(expect_result)
expect(funciton()).not.matchers(expect_result)
This document just gives the list of matchers(Jest_v24.9) and for proper use please checking in the guide url.
(1) Common Matchers
The simplest way to test a value is with exact equality.
-
tobeusesObject.isto test exact equality; -
toEqualcheck the value of an object if equal to expected value;
(2) Truthiness
In tests you sometimes need to distinguish between undefined, null, and false, but you sometimes do not want to treat these differently. Jest contains helpers that let you be explicit about what you want.
-
toBeNullmatches onlynull -
toBeUndefinedmatches onlyundefined -
toBeDefinedis the opposite oftoBeUndefined -
toBeTruthymatches anything that anifstatement treats as true -
toBeFalsymatches anything that anifstatement treats as false
(3) Numbers
Most ways of comparing numbers have matcher equivalents.
-
toBeGreaterThanmatches result>expected -
toBeGreaterThanOrEqualmatches result>=expected -
toBeLessThanmatches result<expected -
toBeLessThanOrEqualmatches result<=expected
(4) Strings
You can check strings against regular expressions with toMatch due to the regular matching rules:
expect('Christoph').toMatch(/stop/);
expect('team').not.toMatch(/I/);
(5) Arrays and Iterables
You can check if an array or iterable contains a particular item using toContain:
expect(sampleArray).toContain('test');
(6) Exceptions
This is just a taste. For a complete list of matchers, check out the reference docs.