使用 TestCafe 端到端测试 Vue.js 应用程序

端到端测试是您测试武器库中最有价值的工具之一,允许您模拟用户在移动应用程序时会做什么,并确定您的应用程序是否正确响应。不幸的是,它也是最困难和耗时的测试方法之一,而通常的工具需要适当的配置和设置,进一步复杂了过程。幸运的是,有一些相对简单的解决方案。

安装

与通常涉及近乎无法管理的依赖量的传统解决方案不同,如 Selenium / WebDriver + 浏览器驱动程序 + 客户端库,TestCafe的整体基于节点,可在一个包中安装。

要在 Vue 应用程序中开始使用它,请通过 Yarn 或 NPM 安装 testcafe. 如果您正在启动新项目,您也可以考虑使用 vuepack 模板 vue-cli

1# Yarn
2$ yarn add testcafe -D
3
4# NPM
5$ npm install testcafe --save-dev

设置

从这里假设你的应用程序有一个开发服务器,可以运行与npm运行dev. webpack-dev-server工作很好。

将新的脚本添加到启动 testcafe 的 package.json 脚本对象中。

1"scripts": {
2  "dev": "...",
3  "test": "testcafe all tests/*.test.js --app \"npm run dev\" --app-init-delay 10000 -S -s screenshots",
4}

这说明Testcafe为:

  • all - 在系统上可以找到的所有浏览器中运行测试. 可选地,将此设置为浏览器名称的单独列表
  • tests/*.test.js - 在测试文件夹中以.test.js 结束的所有文件运行测试
  • --app \"npm run dev\" - 启动应用程序服务器的命令
  • --app-init-delay 10000 - 延迟启动测试套件10秒,等待应用程序服务器加载
  • -S - 拍摄测试失败时的屏幕。

现在我们已经准备好开始写端到端测试了。

你的第一个测试

让我们假设整个应用程序只是 中的一个段落元素,其中包含了Hello World!这个词。

<$>[注意]任何与浏览器进行通信的东西都返回承诺. 使用async / wait来管理到浏览器的呼叫,使测试变得更容易。

 1[label test/example.test.js]
 2// A fixture must be created for each group of tests.
 3fixture(`Index page`)
 4  // Load the URL your development server runs on.
 5  .page('http://localhost:8080');
 6
 7// Create a new test(description, function(testController): <Promise>)
 8test('Body > Paragraph contains "Hello World!"', async testController => {
 9  // Select the paragraph element under the body.
10  // Must use promises (async / await here) for communication with the browser.
11  const paragraphSelector = await new Selector('body > p');
12
13  // Assert that the inner text of the paragraph is "Hello World!"
14  await testController.expect(paragraphSelector.innerText).eql('Hello World!');
15});

控制用户输入

现在,要做任何半体面的端到端测试,你需要能够模拟用户的操作和输入,就像任何好的测试套件一样,TestCafe提供必要的方法来处理这个用例。

 1test('Typing in an input', async testController => {
 2  // Select the input element (Assumes <body><input type="text/></body>")
 3  const inputSelector = await new Selector('body > input[type="text"]');
 4
 5  await testController
 6    // Type the last word of "Hello World!"
 7    .typeText(inputSelector, 'World!')
 8    // Click the beginning of the element. caretPos is the position of the text cursor we want the click to be at.
 9    .click(inputSelector, { caretPos: 0 })
10    // Type the keys, SHIFT+H, e, l, l, o, and SPACE in order to write "Hello ".
11    .keyPress('H e l l o space')
12    // The resulting value should now be "Hello World!"
13    .expect(inputSelector.value).eql('Hello World!');
14});

参考

TestCafe可以做得更多,他们还提供了一些有趣的协议来减少测试重复。 要了解更多,请访问他们的官方网站(https://devexpress.github.io/testcafe)。

Published At
Categories with 技术
Tagged with
comments powered by Disqus