Selenium 测试适用于生产,但不适用于开发

Selenium test works on production but not development

我有一个 Vue.js 应用程序,我想为其编写 selenium 测试。当我 运行 针对已部署的应用程序生产版本进行测试时,测试通过但当 运行 针对本地版本进行测试时失败。

当然,当 运行 在本地 Vue.js 应用程序不是 运行ning 来自构建,而是 运行ning 使用 npm run serve

我在本地有以下 docker compose 设置:

  app:
    build:
      context: .
      dockerfile: ./app.dockerfile
    image: app
    command: npm run serve
    ports:
      - 8080:8080
    volumes:
      - ./app:/app

  selenium:
    image: selenium/standalone-chrome:91.0
    depends_on:
      - app

  e2e-tests:
    build:
      context: .
      dockerfile: ./e2e_tests.dockerfile
    image: e2e-tests
    command: poetry run python ./foo.py
    depends_on:
      - app
      - selenium
    volumes:
      - ./e2e_tests:/app

这是一个基本测试,它使用 e2e-testsselenium 容器来测试互联网上应用程序的已部署生产版本:

from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--window-size=1420,1080")
chrome_options.add_argument("--headless")
driver = webdriver.Remote("http://selenium:4444/wd/hub", options=chrome_options)

driver.get('https://www.example.com')

try:
    assert 'My app title' in driver.title
except AssertionError:
    print('invalid title')

driver.quit()

如果我现在将上述测试更改为使用 app 容器,它只是 Vue 应用程序的本地 运行ning 版本,它会失败,因为标题为空:

driver.get('http://app:8080')

我尝试在 driver.get 之后添加 10 秒 wait 到测试中,但标题仍然是空的。

事实证明,当 selenium 试图从 docker 中调用它时,应用程序正在返回 Invalid Host Header,即使我可以通过浏览器访问该应用程序。一定是一些 docker 相关的特质。

解决方案是更新我的 vue.config.js 如下:

module.exports = {
  devServer: {
    disableHostCheck: true
  }
};

disableHostCheck 解决了这个问题。显然这应该只在开发中使用,因为如果在生产中启用它会带来安全风险。