I'm trying to implement tests in my node.js project. I decided to use mocha / chai / chai-http to test my rest API.
I just have 1 simple file in my test folder:
movie.ts:
import chai from 'chai';
import chaiHttp from 'chai-http';
let app = require('../app');
chai.should();
chai.use(chaiHttp);
declare var process : {
env: {
API_KEY: string
}
}
describe('/GET movies', () => {
it('it should GET all the movies', (done) => {
chai.request(app)
.get('/v1/movies')
.set("Authorization", process.env.API_KEY)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('array');
done();
});
});
});
Here is my dockerfile:
FROM node:latest
WORKDIR /app/
COPY package.json .
RUN npm install
COPY . .
Docker compose:
version: '3.8'
services:
mariadb:
image: mariadb
env_file: ./.env
environment:
MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
MYSQL_USER: $MYSQL_USER
MYSQL_PASSWORD: $MYSQL_PASSWORD
MYSQL_DATABASE: $MYSQL_DATABASE
ports:
- $MYSQL_LOCAL_PORT:$MYSQL_DOCKER_PORT
volumes:
- mysql:/var/lib/mysql
- mysql_config:/etc/mysql
- ./sql/:/docker-entrypoint-initdb.d/
phpmyadmin:
image: phpmyadmin
restart: always
ports:
- 8080:80
environment:
PMA_HOSTS: mariadb
web:
build: .
env_file: ./.env
command: npm start
volumes:
- .:/app/
- /app/node_modules
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
depends_on:
- mariadb
environment:
MYSQL_HOST: mariadb
web-tests:
image: hypescript_web
command: npm test
environment:
MYSQL_HOST: mariadb
depends_on:
- mariadb
- web
volumes:
mysql:
mysql_config:
This test is working but I have 2 problems when I run it during docker compose up cmd.
As you can see I created another container just for the test and I'm not sure if it's the best practice to test my API. web-tests container uses my node.js image built in the docker compose so if I don't have the image already built in my machine I have to comment all my web-tests services and when the image is built then I can uncomment web-tests and I can use it to run mocha tests.
The 2nd problem is that I need to set a timeout to run my test (e.g after 10 seconds) because I build my database at the same time and the first time I'll get database errors because the tests are running and the database init isn't finished. I tried to add a timeout to mocha in the package.json but the timeout is ignored.
"scripts": {
"start": "nodemon -L app.ts",
"debug": "export DEBUG=* && npm run start",
"test": "mocha --timeout 10000 -r ts-node/register test/**/*.ts"
}
I think I'm doing something wrong because it's very heavy to run my API tests. I'd like to runs my tests without comment / uncomment at the first run and add a timeout. How do you do to runs your API tests in docker ?