-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Jest 26 cannot test Web Components #11009
Comments
No longer use LitElement and TypeScript, get exactly the same result. class MyCustomElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' })
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<div class="title">My Custom Title</div>
`
}
}
describe('Playlist', () => {
it('attributes are empty by default', () => {
window.customElements.define('my-custom-element', MyCustomElement)
const customElement = document.createElement('my-custom-element')
expect(customElement.shadowRoot.querySelector('.title').innerHTML).toBe('My Custom Title')
})
}) TypeError: Cannot read property 'innerHTML' of null
17 | const customElement = document.createElement('my-custom-element')
18 |
> 19 | expect(customElement.shadowRoot.querySelector('.title').innerHTML).toBe('My Custom Title')
| ^
20 | })
21 | })
22 |
at Object.<anonymous> (__tests__/test.spec.js:19:12) |
Do you have a reproduce repo ? It is required in the bug template to let others easily help. |
I found the reason, the example is wrong. Use the following code, it can pass the test. class MyCustomElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' })
}
connectedCallback() {
this.shadowRoot.innerHTML = `
<div class="title">My Custom Title</div>
`
}
}
window.customElements.define('my-custom-element', MyCustomElement)
test('test', () => {
document.body.innerHTML = '<my-custom-element></my-custom-element>'
const element = document.querySelector('my-custom-element')
expect(element.shadowRoot.querySelector('.title').innerHTML).toBe('My Custom Title')
})
import { LitElement, html } from 'lit-element'
class MyCustomElement extends LitElement {
render() {
return html`<div class="title">My Custom Title</div>`
}
}
window.customElements.define('my-custom-element', MyCustomElement)
test('test', async () => {
document.body.innerHTML = '<my-custom-element></my-custom-element>'
const element = document.querySelector('my-custom-element')
await Promise.resolve()
expect(element!.shadowRoot!.querySelector('.title')!.innerHTML).toBe('My Custom Title')
}) |
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
Originally posted by @vibaiher in #9606 (comment)
I tried to reproduce this code (pls ignore "!", it is TypeScript):
and this is the result:
The text was updated successfully, but these errors were encountered: