使用 Nightwatch 为 Nuxt 应用编写测试

在这个练习中,我们想要针对 Chrome 浏览器测试我们在上一章(第十二章,创建用户登录和 API 身份验证)中创建的用户登录身份验证。我们想要确保用户可以使用他们的凭据登录并按预期获取他们的用户数据。我们将在保存 Nuxt 应用程序的 /frontend/ 目录中编写测试,因此我们需要相应地修改 package.json 文件并在以下步骤中编写测试:

  1. 通过 npm 安装 ChromeDriver,并将其保存到 package.json 文件中的 devDependencies 选项:

    $ npm install chromedriver --save-dev
  2. Nightwatch 配置文件 nightwatch.json 中,更改启动 URLlocalhost:3000 并进行其他设置,如下面的代码块所示,以便针对 Chrome 进行测试:

    // nightwatch.json
    {
      "src_folders" : ["tests"],
      "webdriver" : {
        "start_process": true,
        "server_path": "node_modules/.bin/chromedriver",
        "port": 9515
      },
      "test_settings" : {
        "default" : {
          "desiredCapabilities": {
            "browserName": "chrome"
          }
        }
      },
      "launch_url": "http://localhost:3000"
    }
  3. 在项目根目录下创建一个 nightwatch.conf.js 文件,用于将驱动程序路径动态设置为服务器路径:

    // nightwatch.conf.js
    const chromedriver = require("chromedriver")
    module.exports = (function (settings) {
      settings.test_workers = false
    
      settings.webdriver.server_path = chromedriver.path
      return settings
    })(require("./nightwatch.json"))
  4. /tests/ 目录中创建一个 login.js 文件,其代码如下:

    // tests/login.js
    module.exports = {
      'Local login test' : function (browser) {
        browser
          .url(browser.launchUrl + '/login')
          .waitForElementVisible('body', 1000)
          .assert.title('nuxt-e2e-tests')
          .assert.containsText('h1', '请登录以查看秘密内容')
          .assert.visible('input[type=text][name=username]')
          .assert.visible('input[type=password][name=password]')
          .setValue('input[type=text][name=username]', 'demo')
          .setValue('input[type=password][name=password]',
            '123123')
          .click('button[type=submit]')
          .pause(1000)
          .assert.containsText('h2', '你好 Alexandre!')
          .end()
      }
    }

    此测试的逻辑与上一节中的测试相同。我们想要确保在登录前后,登录页面上存在某些元素和文本。

  5. 在运行测试之前,在终端上运行位于 localhost:3000localhost:4000NuxtAPI 应用程序,然后在 /frontend/ 目录中打开另一个终端并运行 npm run test。如果测试通过,你将得到以下结果:

    [Login] Test Suite
    ==================
    Running: Local login test
    ✓ Element <body> was visible after 28 milliseconds.
    ✓ Testing if the page title equals "nuxt-e2e-tests" - 4 ms.
    ✓ Testing if element <h1> contains text: "请登录以查看秘密内容" - 27 ms.
    ✓ Testing if element <input[type=text][name=username]> is
      visible - 25 ms.
    ✓ Testing if element <input[type=password][name=password]> is
      visible - 25 ms.
    ✓ Testing if element <h2> contains text: "你好 Alexandre!"
      - 75 ms.
    OK. 6 assertions passed. (1.613s)

    请注意,在运行测试之前,你必须同时运行 Nuxt 应用程序和 API

    你可以在我们的 GitHub 仓库的 /chapter-13/nuxt-universal/nightwatch/ 中找到上述测试。

做得好。你已经完成了这个关于为 Nuxt 应用程序编写测试的简短章节。本章中的步骤和练习为你提供了扩展测试的基本基础,随着你的应用程序变得更大更复杂,你可以进一步完善你的测试。让我们在最后一节中总结一下你在本章中学到的内容。