gpt4 book ai didi

javascript - 使用 JEST 测试 DOM 元素

转载 作者:行者123 更新时间:2023-11-30 19:47:53 25 4
gpt4 key购买 nike

我正在尝试让自己熟悉 JEST,所以我意识到我在这里可能越位了......但我想编写一个测试来验证我的索引页面的标题,我引用了这个文档:https://jestjs.io/docs/en/tutorial-jquery .

这是测试:

import 'whatwg-fetch'
test('H1 in index says Users', () =>{
//Set up our document body - this is probably my problem...
document = fetch("/index.html").then(onSuccess, onError);
//This succeeds:
//document.body.innerHTML ="<h1>Users</h1>"
function onSuccess(response) {
return response.text();
}
function onError(error){
console.log(error);
}
const $ = require('jquery');
expect($("h1").text()).toEqual("Users");
});

这就是我的 index.html 的样子。

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h1>Users</h1>
</body>
</html>

当我尝试获取 index.html 时,expect() 为空。

最佳答案

不熟悉Jest,但是由于fetch是异步的,在then子句之外是无法获取到fetch结果的。考虑将 expect 放在 onSuccess 中。请看https://jestjs.io/docs/en/asynchronous.html例如处理异步测试。

此外,获取 html 不会返回该 html 文件的 DOM 对象,而是返回原始文本内容,因此 jQuery 将无法工作。您需要通过例如 DOMParser 将该原始文本解析为 DOM,并对 DOM 执行测试。

最后,你需要导入的任何东西都应该放在文件的顶部,所以将 var $ = require('jquery') 移到测试函数之外

示例代码(未测试)

import 'whatwg-fetch'
import $ from "jquery"

test('H1 in index says Users', () =>{
function onSuccess(response) {
const rawHTML = response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(rawHTML, 'text/html');

const h1Text = $(doc).find('h1').text();
expect(h1Text).toEqual('Users');
done();
}

function onError(error){
console.log(error);
}

fetch("/index.html").then(onSuccess, onError);
});

关于javascript - 使用 JEST 测试 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54779034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com