Testing API against your API documentation within docker

This article will show you how to setup testing environment within a docker network. We will be using dredd as our testing tools.

Your API documentation

Here is a sample API Blueprint document

1
2
3
4
5
6
7
8
9
10
11
12
13
FORMAT: 1A

# Tsum Tsum Status

## Group Health Check

### Ping [GET /ping]

+ Response 200 (application/json; charset=utf-8)

+ Body

{"message": "OK"}

Simple Response with express

We will create a simple express application

1
2
3
4
5
6
7
8
9
import express from "express";

app = express();

app.get("/ping", function(req, res) {
res.json({ message: "OK" });
});

app.listen(3000);

Setup dredd.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
dry-run: null
hookfiles: null
language: nodejs
sandbox: false
server: null
server-wait: 3
init: false
custom: {}
names: false
only: []
reporter: [html]
output: [./report/index.html]
header: []
sorted: false
user: null
inline-errors: false
details: false
method: []
color: true
level: info
timestamp: false
silent: false
path: []
hooks-worker-timeout: 5000
hooks-worker-connect-timeout: 1500
hooks-worker-connect-retry: 500
hooks-worker-after-connect-wait: 100
hooks-worker-term-timeout: 5000
hooks-worker-term-retry: 500
hooks-worker-handler-host: 127.0.0.1
hooks-worker-handler-port: 61321
config: ./dredd.yml
blueprint: ./docs/spec.apib
endpoint: 'http://api:3000'

Noted that our endpoint is http://api:3000 since we are testing with a docker network.

Setup docker-compose.itest.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
version: '3'
services:
api:
build: .
command: npm run debug
volumes:
- './dist:/server/dist'
itest:
image: apiaryio/dredd
volumes:
- './docs:/docs'
- './dredd.yml:/dredd.yml'
- './report:/report'
depends_on:
- api

Setup Makefile

1
2
3
4
5
6
7
8
.PHONY: test

test:
@echo Start testing
@docker-compose -f ./docker-compose.itest.yml build
@docker-compose -f ./docker-compose.itest.yml up -d api
@docker-compose -f ./docker-compose.itest.yml up --exit-code-from itest itest
@docker-compose -f ./docker-compose.itest.yml down

Run Test

1
make test

Conclusion

We can expand this setup to add mongodb, mysql or any other database.

Since we are testing in docker, each test will be clean.

Furthermore, you ensure your API document is verbose and accurate enough or dredd to run tests.

Share Comments