【问题标题】:How to run unit tests inside Docker container如何在 Docker 容器中运行单元测试
【发布时间】:2023-03-21 17:45:01
【问题描述】:

我创建了一个运行我的 Angular 项目的 docker 容器,现在我试图在容器内运行我的单元测试,但没有成功。我需要一个无头浏览器来运行我的测试,而 PhantomJS 对我来说太有问题了,在运行测试时也会给出不同的结果。

在这里,我提供我的 Dockerfile:

# download (or use if it's in cache) the latest official image from node
FROM node:latest

# create directory in the container and set all privileges
RUN mkdir -p /usr/src/app && chmod 777 /usr/src/app

# make the directory available for following commands
WORKDIR /usr/src/app

# copy all local's frontend content to the WORKDIR
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

CMD ["npm", "start"]

我尝试使用 Headless Chrome,但它仍然需要一些我不知道该怎么做的更多配置。有人有什么想法吗?

【问题讨论】:

  • 几个月前,我遇到了无头浏览器的问题,一些测试失败了,因为它无法将浏览器滚动到我试图查看它们是否存在的元素。如果您有一些测试失败,请记住这一点。无论如何,您为什么要运行 ng serve 而不是 ng test?
  • 因为我稍后会运行“测试”命令
  • 你是使用 Selenium webdriver for NodeJS 还是使用 protactor?
  • 我正在使用预配置的业力运行测试,因为我使用的是 Angular CLI。我真的不知道这两个中的哪一个被使用了。怎么查?

标签: angular docker karma-jasmine


【解决方案1】:

经过大量调查,我找到了一种方法:

我在前端 Dockerfile 中安装了 Chrome:

RUN wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo 'deb http://dl.google.com/linux/chrome/deb/ stable main' >> /etc/apt/sources.list
RUN apt-get update && apt-get install --no-install-recommends -y google-chrome-stable

我使用无头 Chrome 进行测试,并在 karma.config 中进行了正确配置:

browsers: ['Chrome_without_sandbox'],
customLaunchers: {
  Chrome_without_sandbox: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox'] // with sandbox it fails under Docker
  }
},

【讨论】:

    【解决方案2】:

    如果您使用 Selenium,我建议您创建一个不同的容器来执行 selenium 测试,我们将其命名为 selenium-container。由于您使用的是 Node,因此有一个现有的 selenium webdriver for node,您可以在其中编写单元测试。

    除了该容器,您还可以使用 the chrome standalone server 作为无头浏览器,以便您可以从 selenium-container 执行单元测试,我们将其称为 chrome-container

    在编写单元测试时,您可以通过以下方式连接到无头浏览器服务器来开始测试:

    var driver = new webdriver.Builder()
        .forBrowser('chrome')
        .usingServer('http://localhost:4444/wd/hub')
    

    这只是为了让您开始,API 有详细的文档并且易于使用,以便编写您的测试。

    最好将单元测试与您的 Angular 项目隔离开来,这样它们就不会以任何方式相互干扰。使用docker compose 只需一个命令即可开始测试。你的docker-compose.yml 可能看起来像这样:

    version: '3'
    services:
      angular-app:
        build:
          context: .
          dockerfile: Dockerfile
      selenium_container: 
        build:
          context: .
          dockerfile: Dockerfile.selenium.test
        depends_on:
          - chrome-container
          - angular-app
      chrome-container:
        image: selenium/standalone-chrome:3.4.0-einsteinium
    

    【讨论】:

    • 谢谢。我会试一试,因为我还不精通 Docker,我会在接下来的几天里给你更新。
    • @PanosVakalopoulos 那么这是学习Docker核心概念的好方法,例如运行多个容器,将它们链接在一起,以及docker-compose,祝你好运!
    • 为什么我要调查 selenium,因为我现在正在工作,只是为了进行单元测试? selenium webdriver 不是只需要 e2e 测试吗?
    猜你喜欢
    • 2017-10-30
    • 2020-04-22
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    相关资源
    最近更新 更多