# 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.jsoncorrectly)./node_modules/.bin/jestwill run all test files it can find../node_modules/./bin/jest name_of_filewill test a specific file.
- Walk through
Toy.test.js- Notice that you can use either
itortest - Notice the
.vs#convention. - Notice
toMatchfor Strings.
- Notice that you can use either
- Walk through
MemoryToyDB.test.js- Notice
toBeTruthy(notnull, notundefined, not empty string, etc.) - Notice
toEqualto compare objects.
- Notice
- Matchers
toBeexact equalitytoEqualrecursive equality of arrays and objects.nullandundefinedare different.toBeTruthyandtoBeFalsytoContainfor 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
allToyssimply produces a local list of toys (rather than hitting the DB). reqandresare mock objects passed to the controller methods. (mocks so we can spy on how they are used.)- in the
#indextest, notice how the use of mocks lets us verify that we are correctly passing the value returned byallToysto the templating engine. - Notice the use of
asyncwhen testing functions that useawait.
- Notice
- Other tricks
test.onlyto temporarily one one test only.- Testing callbacks: https://jestjs.io/docs/asynchronous