javascript - 测试更新 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 函数?
解决方案
我通常使用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 的信息:
- 首先安装 jest-puppeteer
yarn add --dev jest-puppeteer
- 在您的 Jest 配置中指定预设:
{
"preset": "jest-puppeteer"
}
- 写你的测试
describe('Google', () => {
beforeAll(async () => {
await page.goto('https://google.com');
});
it('should be titled "Google"', async () => {
await expect(page.title()).resolves.toMatch('Google');
});
});
推荐阅读
- mysql - SQL插入选择依赖于其他表
- c# - 如何在单个节点中获取 XML 标记
- katalon-studio - 存储过程的 Katalon Studio 数据库检查点不起作用
- regex - Flex 中的正则表达式错误
- javascript - 解构对象在属性名称中具有连字符
- python - 将数据框与 dict 值一起使用时出现 Pandas 错误
- python - 如何在张量流中并行加载数据?
- javascript - 无法使用 NetBeans 将 JavaScript 加载到 Node.js 中的 HTML 页面
- javascript - 将表格的 2 行设置为最后一行
- mysql - 如何绑定使用变量作为 Codeigniter 中 LIMIT 参数的查询