Debian Codegraph @

packages/labs/virtualizer/src/test/scenarios/immediate-rerender.test.ts

raw
1 /**
2 * @license
3 * Copyright 2022 Google LLC
4 * SPDX-License-Identifier: BSD-3-Clause
5 */
6
7 import {ignoreBenignErrors} from '../helpers.js';
8 import {html, LitElement} from 'lit';
9 import {customElement} from 'lit/decorators.js';
10 import {LitVirtualizer} from '../../lit-virtualizer.js';
11 import '../../lit-virtualizer.js';
12 import {expect, html as testingHtml, fixture} from '@open-wc/testing';
13
14 interface ExampleItem {
15 text: string;
16 }
17
18 @customElement('my-example')
19 export class MyExample extends LitElement {
20 items: ExampleItem[] = new Array(100)
21 .fill('')
22 .map((_, i) => ({text: `Item ${i}`}));
23
24 render() {
25 return html`
26 <slot @slotchange=${this._onSlotChange} style="display: none;"></slot>
27 <lit-virtualizer
28 .items=${this.items}
29 .renderItem=${(item: ExampleItem) => html`<p>${item.text}</p>`}
30 ></lit-virtualizer>
31 `;
32 }
33
34 _onSlotChange() {
35 this.requestUpdate();
36 }
37 }
38
39 // This is one minimal repro case for https://github.com/lit/lit/issues/3481.
40 // This issue occurs when something triggers an immediate re-render of virtualizer
41 // and an attempt to tear down some internal state before the async initialization
42 // code for that state had run. In this repro, a slotchange event triggers
43 // the re-render, but other minimal repro cases are probably possible. The
44 // fix we've identified is some straightforward guard code to ensure that we
45 // don't try to tear down state that hasn't yet been set up. It's possible
46 // we'll end up wanting to short-circuit immediate re-renders earlier (before
47 // they reach this guard code), but for now this fix seems sufficient.
48 describe("Don't fail when rerendering before initialization is complete", () => {
49 ignoreBenignErrors(beforeEach, afterEach);
50
51 let errorOccurred = false;
52
53 function recordError(err: PromiseRejectionEvent) {
54 if (err.reason.stack.indexOf('Virtualizer') > -1) {
55 errorOccurred = true;
56 }
57 }
58
59 addEventListener('unhandledrejection', recordError);
60
61 it('should render without throwing an error', async () => {
62 const example = await fixture(
63 testingHtml`<my-example>Slot me!</my-example>`
64 );
65 await customElements.whenDefined('lit-virtualizer');
66 const virtualizer = example.shadowRoot!.querySelector('lit-virtualizer')!;
67 expect(virtualizer).to.be.instanceOf(LitVirtualizer);
68 await virtualizer.layoutComplete;
69 removeEventListener('unhandledrejection', recordError);
70 expect(errorOccurred).to.equal(false);
71 });
72 });