问题
嘿,我没怎么用过 Docker - 我试图通过 Dockerfile 运行我的 Jest 测试。但是,在尝试构建镜像时,我遇到了以下错误:
错误信息
Step 13/16 : RUN if [ "$runTests" = "True" ]; then RUN npm test; fi
---> Running in ccdb3f89fb79
/bin/sh: RUN: not found
Dockerfile
FROM node:10-alpine as builder
ARG TOKEN
WORKDIR /app
ARG runTests
COPY .npmrc-pipeline .npmrc
COPY package*.json ./
RUN npm install
COPY . .
RUN rm -f .npmrc
ENV PORT=2000
ENV NODE_ENV=production
RUN if [ "$runTests" = "True" ]; then \
RUN npm test; fi
RUN npm run build
EXPOSE 2000
CMD ["npm", "start"]
我使用的命令来构建镜像是这个,目的是只有在runTests=True时才能运行测试。
docker build -t d-image --build-arg runTests="True" --build-arg "MY TOOOOOKEN"
仅使用Dockerfile是否可以实现这一点?还是必须同时使用docker-compose呢?
条件语句似乎工作得很好。
不可能有两个CMD命令
我尝试了以下解决方法(但它没有起作用): Dockerfile
FROM node:10-alpine as builder
ARG TOKEN
WORKDIR /app
ARG runTests
COPY .npmrc-pipeline .npmrc
COPY package*.json ./
RUN npm install
COPY . .
RUN rm -f .npmrc
ENV PORT=3000
ENV NODE_ENV=production
RUN npm run build
EXPOSE 3000
CMD if [ "$runTests" = "True" ]; then \
CMD ["npm", "test"] && ["npm", "start"] ;fi
目前我没有从测试中得到任何输出,但它似乎是成功的。
进展
我已经有了一些进展,当我构建镜像时,实际上测试正在运行。我还决定使用RUN命令来运行测试,这样它们就可以在构建步骤中运行。
Dockerfile:
FROM node:10-alpine as builder
ARG TOKEN
WORKDIR /app
COPY .npmrc-pipeline .npmrc
COPY package*.json ./
RUN npm install
COPY . .
RUN rm -f .npmrc
ENV PORT=3000
ENV NODE_ENV=production
RUN npm run build
RUN npm test
EXPOSE 3000
错误:
FAIL src/pages/errorpage/tests/accessroles.test.jsx
● Test suite failed to run
Jest encountered an unexpected token
This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/en/configuration.html
Details:
我认为docker build
过程在Dockerfile中拷贝并安装package.json
文件后,似乎没有使用其中的jest:{...}
配置。有何想法?
if ... then ... fi
结构中重复了Docker的RUN
/CMD
行。你不需要这样做,只需删除第二个RUN
/CMD
即可。(构建步骤将无条件运行,但如果测试失败,则不会执行任何操作。) - David Maze