# Unit testing with Jest
- Jest is one of many JavaScript unit testing frameworks.
- Others include
- Simple to set up.
npm install jest --save-dev
- Simple to run
npm test
(if you set uppackage.json
correctly)./node_modules/.bin/jest
will run all test files it can find../node_modules/./bin/jest name_of_file
will test a specific file.
- Walk through
Toy.test.js
- Notice that you can use either
it
ortest
- Notice the
.
vs#
convention. - Notice
toMatch
for Strings.
- Notice that you can use either
- Walk through
MemoryToyDB.test.js
- Notice
toBeTruthy
(notnull
, notundefined
, not empty string, etc.) - Notice
toEqual
to compare objects.
- Notice
- Matchers
toBe
exact equalitytoEqual
recursive equality of arrays and objects.null
andundefined
are different.toBeTruthy
andtoBeFalsy
toContain
for iterable objects.
Mocking / Testing Controllers
- Testing controllers is more of an integration test.
- You are mostly verifying that the correct methods are called with the correct parameters.
- Sometimes there is logic to unit tests, sometimes there isn’t.
- When testing controllers, we want to mock the model and view
- Make sure they are called properly, but we don’t actually want to run the model/view code.
- Walk through
ToyController.test.js
- Notice
jest.mock('../Toy');
beforeEach
- the mock of
allToys
simply produces a local list of toys (rather than hitting the DB). req
andres
are mock objects passed to the controller methods. (mocks so we can spy on how they are used.)- in the
#index
test, notice how the use of mocks lets us verify that we are correctly passing the value returned byallToys
to the templating engine. - Notice the use of
async
when testing functions that useawait
.
- Notice
- Other tricks
test.only
to temporarily one one test only.- Testing callbacks: https://jestjs.io/docs/asynchronous