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 up package.json
correctly)
npx jest
will run all test files it can find (alternatively ./node_modules/.bin/jest
)
./node_modules/./bin/jest name_of_file
will test a specific file.
- Walk through
Toy.test.js
- Notice that you can use either
it
or test
- Notice the
.
vs #
convention.
- Notice
toMatch
for Strings.
- Walk through
MemoryToyDB.test.js
- Notice
toBeTruthy
(not null
, not undefined
, not empty string, etc.)
- Notice
toEqual
to compare objects.
- Matchers
toBe
exact equality
toEqual
recursive equality of arrays and objects.
null
and undefined
are different.
toBeTruthy
and toBeFalsy
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
and res
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 by allToys
to the templating engine.
- Notice the use of
async
when testing functions that use await
.
- Other tricks