Testing NodeJS APIs pt. III: set up Jest + Supertest and tasks
2 min readDec 2, 2019
Now that we have a server and an API we can set up our test environment/tasks.
Install depencencies
npm i --save-dev cross-env supertest jest
- Jest: testing framework, with a in-built test runner, assertion library and mocking support(and more)
- Supertest: library for testing Node.js HTTP servers, enabling to programmatically send HTTP requests
- cross-env: library that allows to set environment variables in any OS
Now, let's add a test task in the package.json:
"scripts": {
"test": "cross-env NODE_ENV=test jest — testTimeout=10000"
}
If you try to run this task you will have this output:
npm run test
> cross-env NODE_ENV=test jest — testTimeout=10000
No tests found, exiting with code 1
So let's create a simple test to check if our test setup is correct. Create a test/ folder and there, a sample.test.js:
describe('Sample Test', () => {
it(‘should test that true === true’, () => {
expect(true).toBe(true)
})
})
Now, run again the task:
npm run test
> cross-env NODE_ENV=test jest — testTimeout=10000
PASS test/sample.test.js
Sample Test
✓ should test that true === true (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.055s
Ran all test suites.
Now we are ready to write our real tests in the next part!