繁体   English   中英

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

[英]How to find an element existence in document in javascript

我只是创建了一个 html 文档。 我开始使用jest进行测试。 但得到无效的输出。 通过jest测试文档中元素存在的正确方法是什么?

这是我的 html:

<body>
<h2>Title</h2>
<input type="file" name="" class='title'>
<script src="./index.js"></script>
</body>

我的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 = '';
    });

}

我的测试规范:

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)

测试文档中现有元素的正确方法是什么?

提前致谢。

我会尝试,因为您已经尝试使用querySelector查找元素

...
expect((h2 !== null)).toBe(true);
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM