Now, we write tests for the server! Luckily, these tests are a little easier to write, especially since this sample application does not have a database.
Similar to our frontend Jest tests, we need to setup backend jest tests.
Copy the following to jest.server.json
:
{
"collectCoverageFrom": [
"**/*.js"
],
"coveragePathIgnorePatterns": [
"/node_modules/",
"/__tests__/"
],
"roots": [
"server"
],
"testEnvironment": "node"
}
Next, let's add the test command to package.json
:
"test:server": "jest --config jest.server.json",
Test it out by running npm run test:server
!
Our first method, getSha
, takes a string and returns a commit sha in hex.
Let's test that the commit sha returned from any valid input returns a valid hex.
You could use require('assert')
or Jest's built-in expect.
The test is scaffolded here: server/_tests_/shas.js
We should also be thinking about all the test cases.
What happens if someone passes something that isn't a string to getSha()
?
We should add tests to make sure those cases are properly handled: they should
either return an informative message in the form of a TypeError
.
supertest is a testing library
built on top of superagent that
makes testing simple API endpoints dead simple.
Let's implement it for our POST /api/v1/shas
route.
The test is scaffolded here: server/_tests_/api.js
Like our jsdom tests, we need to add the test commands to our CircleCI config:
- run: npm run test:server -- --coverage
- run: npx codecov
- When you need to test multiple API calls in the same session, user
require('superagent').agent()
- Like with your React jest tests, be sure to set
--maxWorkers