测试你的前端代码:可视化测试

1,345 阅读1分钟
原文链接: web.jobbole.com

现在我们已经设置好浏览器和 Eyes,我们可以写测试了,这和我们的端到端测试非常像:

it('should look good', async function () {
   await driver.get('http://localhost:8080')
 
   await eyes.checkWindow('Initial Page')
 
   const digit4Element = await driver.findElement(By.css('.digit-4'))
   const digit2Element = await driver.findElement(By.css('.digit-2'))
   const operatorMultiply = await driver.findElement(By.css('.operator-multiply'))
   const operatorEquals = await driver.findElement(By.css('.operator-equals'))
 
   await digit4Element.click()
   await digit2Element.click()
   await operatorMultiply.click()
   await digit2Element.click()
   await operatorEquals.click()
 
   await eyes.checkWindow('After calculating 42 * 2 =')
 })

这个系列的前一篇文章中的端到端测试相比,你可以看到它很像,但更短。代码中主要的区别是对特定元素的验证被一行简单的代码代替了:

await eyes.checkWindow(‘’)

在端到端测试中,我们是这样做的:

await retry(async () => {
  const displayElement = await driver.findElement(By.css('.display'))
  const displayText = await displayElement.getText()
 
  expect(displayText).to.equal('0')
})

我们通过重试等待页面“稳定”。但进行可视化测试的时候,你不需要等待页面可见 —— eyes.checkWindow 会帮你干这个事情!

eyes.checkWindow 会截取页面图像并将之与前端测试产生的基准图像进行比较(参阅下面的小节“运行可视化测试”)。如果比较结果是新图像与基准等价,则测试成功,否则测试失败。