[英]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.