首页 > 解决方案 > 测试更新 DOM 的 javascript

问题描述

我是 Web 测试的新手,想知道如何测试读取和更新 DOM 的 javascript。

function otherFunction(string) {
// do some processing and return processed data
}

function domUpdater() {
  var string = document.getElementById("input").value;
  document.getElementById("output").innerHTML = otherFunction(string);
}

我可以轻松测试接受和输入并返回输出的 otherFunction。

expect(otherFunction("input1")).to.be("expected1");
expect(otherFunction("input2")).to.be("expected2");

我不清楚如何测试修改 DOM 的 domUpdater 函数?

标签: javascripthtmlunit-testingtestingjestjs

解决方案


我通常使用jsdom, 就我而言,因为我使用的是 mocha 它看起来像这样(使用jsdom-mocha):

var jsdom = require('mocha-jsdom')
var expect = require('chai').expect

describe('mocha tests', function () {

  jsdom()

  it('has document', function () {
    var div = document.createElement('div')
    expect(div.nodeName).eql('DIV')
  })

})

但是,如果您负担得起(测试往往需要更长的时间才能运行),我建议您考虑在无头浏览器中运行您的测试,使用类似Puppeteer的东西。

一个快速的谷歌搜索产生了这个关于如何用 puppeteer 运行 jest 的信息:

  1. 首先安装 jest-puppeteer
yarn add --dev jest-puppeteer
  1. 在您的 Jest 配置中指定预设:
{
 "preset": "jest-puppeteer"
}
  1. 写你的测试
describe('Google', () => {
  beforeAll(async () => {
    await page.goto('https://google.com');
  });

  it('should be titled "Google"', async () => {
    await expect(page.title()).resolves.toMatch('Google');
  });
});

推荐阅读