Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript文档中查找元素的存在性_Javascript_Jestjs - Fatal编程技术网

如何在javascript文档中查找元素的存在性

如何在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

我只是创建了一个html文档。我开始使用
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);
...