How to test custom web component with jest?

后端 未结 5 724
栀梦
栀梦 2021-01-06 08:54

I would like to test some custom web components and use jest.js as test runner (due to its support for ES6).

Chromium supports commands like

window.c         


        
5条回答
  •  梦毁少年i
    2021-01-06 09:18

    JSDOM 16.2 includes basic support for custom elements and is available in Jest 26.5 and above. Here's a simple Jest test that shows it working:

    customElements.define('test-component', class extends HTMLElement {
        constructor() {
            super();
            const p = document.createElement('p')
            p.textContent = 'It works!'
            this.appendChild(p)
        }
    })
    
    test('custom elements in JSDOM', () => {
        document.body.innerHTML = `

    Custom element test

    ` expect(document.body.innerHTML).toContain('It works!') })

    Output:

    $ jest
    
    PASS  ./test.js
    ✓ custom elements in JSDOM (11 ms)
    
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        1.409 s
    Ran all test suites.
    

    Note not all features are supported yet, notably shadow DOM does not work.

提交回复
热议问题