如何在Docker中为Node.js应用程序设置单元测试?
我正在尝试为我的节点应用程序运行摩卡单元测试.该应用程序是由docker映像构建的.
I am trying to run mocha unit test for my node application. The application is built by a docker image.
Docker映像:
FROM node:6.10.0-alpine
RUN mkdir -p /app
WORKDIR /app
COPY package.json /app
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "start"]
Docker撰写:
version: "3"
services:
web: #### nodejs image
build: .
volumes:
- ./app/
ports:
- "3000:3000"
depends_on:
- db
db:
build: ##### postgres db image
context: .
dockerfile: dbDockerfile
ports:
- 5432:5432
可以按预期构建和运行安装程序.问题不在于我不确定如何运行mocha
之类的单元测试命令来执行测试.
The setup can be built and worked as expected. The problem is not I am sure how to run unit test commands like mocha
to perform the test.
我看到了一个名为dockunit
的模块,但是我不确定这是否是目前的唯一方法.有人可以帮我这个忙吗?
I see a module called dockunit
but I am not sure if that's the only way for now. Can anyone help me out about this?
使用docker
(和docker-compose
),您可以在容器中运行任意命令. Dockerfile
定义了没有指定其他命令时运行的默认命令,但这并不意味着它是唯一可以运行的命令.
With docker
(and docker-compose
), you can run arbitrary commands in a container. The Dockerfile
defines the default command that is run when no other command is specified, but that doesn't mean it's the only one you can run.
在您的情况下:如果未指定其他命令,则运行npm start
.当您执行docker-compose up
时会发生这种情况.
In your case: npm start
is run when no other command is specified. That happens when you do docker-compose up
.
但是,您可以使用docker run
或docker-compose run
运行任何命令.对于您的测试,可能看起来像这样:docker-compose run web mocha
.
But, you can run any command using docker run
or docker-compose run
. For your tests, that might look like this: docker-compose run web mocha
.
There is a slight difference in up
and run
, and I encourage you to read up on it: Should I use docker-compose start up or run?
这对您入门有帮助吗?