如何在javascript文档中查找元素的存在性
我只是创建了一个html文档。我开始使用如何在javascript文档中查找元素的存在性,javascript,jestjs,Javascript,Jestjs,我只是创建了一个html文档。我开始使用jest进行测试。但是得到的是无效的输出。通过jest测试文档中元素存在的正确方法是什么 这是我的html: <body> <h2>Title</h2> <input type="file" name="" class='title'> <script src="./index.js"></script> </body> 我的测试规范: describe('first t
jest
进行测试。但是得到的是无效的输出。通过jest
测试文档中元素存在的正确方法是什么
这是我的html:
<body>
<h2>Title</h2>
<input type="file" name="" class='title'>
<script src="./index.js"></script>
</body>
我的测试规范:
describe('first test', () => {
it('should contain h2 element', () => {
const h2 = document.querySelector('h2');
expect(document.contains(h2)).toBe(true);
});
});
但下面是一个错误:
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)
expect(received).toBe(expected)//Object.is相等
预期:正确
收到:假
3 |它('应该包含h2元素',()=>{
4 | const h2=document.querySelector('h2');
>5 | expect(document.contains(h2)).toBe(true);
| ^
6 | });
7 |
8 | });
反对。(索引规范js:5:39)
测试文档中现有元素的正确方法是什么
提前感谢。我会尝试,因为您已经尝试使用
querySelector
...
expect((h2 !== null)).toBe(true);
...
这看起来像是
document.contains(h2)
返回的内容的问题,而不是相等性测试,错误表明预期:true Received:false
这可能是一个愚蠢的答案,但如果((让el=document.querySelector('h2'))/*做你的事*/,你为什么不做?或者expect((h2!==null)).toBe(true)
`expect(document.body.contains(h2)).toBe(true);`->这是行不通的。但是expect((h2!==null)).toBe(true)代码>->这有助于expect((h2!==null)).toBe(true)代码>无效。仅适用于false
params@3gwebtrain如果您尝试expect(!!h2)。
expect(!!h2)).toBe(true)代码>-不走运<代码>预期:接收到正确:错误
@3gwebtrain您能控制台日志(h2)
?你能看到你的元素吗?
...
expect((h2 !== null)).toBe(true);
...