[英]How to find an element existence in document in javascript
I simply created a html document.我只是创建了一个 html 文档。 i start to test using
jest
.我开始使用
jest
进行测试。 But getting invalid output.但得到无效的输出。 what is the correct way to test the element existence in document by
jest
?通过
jest
测试文档中元素存在的正确方法是什么?
here is my html:这是我的 html:
<body>
<h2>Title</h2>
<input type="file" name="" class='title'>
<script src="./index.js"></script>
</body>
my js code :我的js代码:
window.onload = () => {
const title = document.querySelector('h2');
title.style = 'border:1px solid red';
const input = document.querySelector('input');
input.addEventListener('change', (event) => {
const file = event.srcElement.files;
input.value = '';
});
}
my test spec:我的测试规范:
describe('first test', () => {
it('should contain h2 element', () => {
const h2 = document.querySelector('h2');
expect(document.contains(h2)).toBe(true);
});
});
but getting below error:但得到以下错误:
expect(received).toBe(expected) // Object.is equality
Expected: true
Received: false
3 | it('should contain h2 element', () => {
4 | const h2 = document.querySelector('h2');
> 5 | expect(document.contains(h2)).toBe(true);
| ^
6 | });
7 |
8 | });
at Object.<anonymous> (index.spec.js:5:39)
what is the correct approach to test my existing element in document?测试文档中现有元素的正确方法是什么?
Thanks in advance.提前致谢。
I would try as you've already tried to find the element with querySelector
我会尝试,因为您已经尝试使用
querySelector
查找元素
...
expect((h2 !== null)).toBe(true);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.