Test Files
Loading "Move Tests Into Modules"
Run locally for transcripts
Right now, we keep our tests in the same file as the code they verify. If someone imports
greet.ts
, they will also import and run the tests, which is not something we want in production (we should be concerned with the tests, not our users).A far more resilient strategy is to keep the tests separate from the source code. By doing so, we keep the source clean while also having freedom to structure and evolve the tests (e.g. split them by behavior, move them around, and delete them).
There are multiple ways to structure test files. You can keep them next to the source files, or put them in a designated
test
/__test__
directories. Those are stylistic choices, and as with any such choices, consistency is the only thing that matters.It is a good practice, however, to keep the association between the source code and the test file. Often, this is done by naming the test similar to the module it verifies and adding a
.test.ts
or .spec.ts
suffix to it.├── greet.ts
└── greet.test.ts
👨💼 In this one, your task will be to move all the existing tests into a designated test file.
It's going to involve moving code around but don't worry, Kody the Koala is here to help!
🐨 Once the
greet.test.ts
file is created, move the existing tests from greet.ts
there.Next, you have to make the
test()
and expect()
functions be available globally for the greet.test.ts
file. To do that, use the --import
option on the Node.js CLI.Then, move the declaration for the
test()
and expect()
functions to the newly created setup.ts
file.Finally, to run the tests, use the
--import
option of the Node.js CLI to reference the setup.ts
as a global file to include:npx tsx --import ./setup.ts greet.test.ts