- Testing overview (slides)
- Intro to Mocha, chai, and supertest (slides)
- Debugging tests (extra)
- Tonight's assignment (slides)
- Four phases of a test
- Setup data for the request and the expected result
- Send request to app using supertests
- Check actual response vs expected response using chai assertions
- Teardown any setup data
- Testing mindset: Not "Of course it will work". Instead: "How many ways can I make it fail?"
- Two test types:
- Complete specification - Several assertions. Verifies proper operation.
- Single assertion - Explores only one aspect of behavior. Easier & faster to debug.
- How much testing is enough?
- Happy path/smoke test (can be mult-assertion)
- Error handling
- Validation (happy & unhappy)
- Query params required fields
- Query param type and range
- Body contents (for POST and PATCH)
- Validation (happy & unhappy)
- Be aware of dimishing returns - don't test very unlikely cases or included libraries
As Tolstoy didn't say, "Every unhappy path is unhappy in its own way."
A few extra notes about debugging your tests
- Create a new "Mocha Tests" launch configuration
- Edit that launch.json configuration so that the
args
property isbdd
instead oftdd
- Set your breakpoint after the response comes back and look around
Your launch.json file will include a configuration like this:
{
"type": "node",
"request": "launch",
"name": "Mocha Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd", // changed
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test"
],
"internalConsoleOptions": "openOnSessionStart",
"skipFiles": [
"<node_internals>/**"
]
},
Note: JSON doesn't like comments so be sure to remove the one above.
Here's the best sequence to use when developing express API server apps in a full stack environment (with a react client at hand):
Tests, then postman, then client.
- Work endpoint by endpoint, one at a time. Don't skip around.
- Write one test & make it run, using
npm test
and the vscode debugger. - Repeat that cycle until the API endpoint has all the functionality required.
- Use
npm start
to run the server and use postman to completely verify endpoint functionality - Update both tests and server code to fix any issues and run
npm test
to verify functionality - Run the server and verify that the react client uses the API endpoint correctly.
If you find an API bug with postman or your react client, it means your test coverage is inadequate.
- Update your tests to expose the situation you discovered
- Make sure the tests fail (and thus expose the bug), then fix the server code
- Reverify with postman
- Reverify with your react client.