|
1 |
| -import { describe, test } from "vitest"; |
| 1 | +import { describe, expect, test, vi } from "vitest"; |
| 2 | +import { createCachedBounds } from "./createCachedBounds"; |
2 | 3 |
|
3 | 4 | describe("createCachedBounds", () => {
|
4 |
| - test("have tests", () => { |
5 |
| - // TODO Write tests |
| 5 | + test("should lazily measure items before the requested index", () => { |
| 6 | + const itemSize = vi.fn((index: number) => 10 + index); |
| 7 | + const cachedBounds = createCachedBounds({ |
| 8 | + itemCount: 10, |
| 9 | + itemProps: {}, |
| 10 | + itemSize |
| 11 | + }); |
| 12 | + |
| 13 | + expect(itemSize).not.toHaveBeenCalled(); |
| 14 | + expect(cachedBounds.size).toBe(0); |
| 15 | + |
| 16 | + expect(cachedBounds.get(2)).toEqual({ |
| 17 | + scrollOffset: 21, |
| 18 | + size: 12 |
| 19 | + }); |
| 20 | + expect(itemSize).toHaveBeenCalledTimes(3); |
| 21 | + expect(cachedBounds.size).toBe(3); |
| 22 | + |
| 23 | + expect(cachedBounds.get(3)).toEqual({ |
| 24 | + scrollOffset: 33, |
| 25 | + size: 13 |
| 26 | + }); |
| 27 | + expect(itemSize).toHaveBeenCalledTimes(4); |
| 28 | + expect(cachedBounds.size).toBe(4); |
| 29 | + }); |
| 30 | + |
| 31 | + test("should cached measured sizes", () => { |
| 32 | + const itemSize = vi.fn(() => 10); |
| 33 | + |
| 34 | + const cachedBounds = createCachedBounds({ |
| 35 | + itemCount: 10, |
| 36 | + itemProps: {}, |
| 37 | + itemSize |
| 38 | + }); |
| 39 | + |
| 40 | + expect(itemSize).not.toHaveBeenCalled(); |
| 41 | + expect(cachedBounds.size).toBe(0); |
| 42 | + |
| 43 | + cachedBounds.get(9); |
| 44 | + |
| 45 | + expect(itemSize).toHaveBeenCalledTimes(10); |
| 46 | + expect(cachedBounds.size).toBe(10); |
| 47 | + |
| 48 | + for (let index = 0; index < 10; index++) { |
| 49 | + cachedBounds.get(index); |
| 50 | + } |
| 51 | + |
| 52 | + expect(itemSize).toHaveBeenCalledTimes(10); |
| 53 | + expect(cachedBounds.size).toBe(10); |
| 54 | + }); |
| 55 | + |
| 56 | + test("should gracefully handle an empty cache", () => { |
| 57 | + const cachedBounds = createCachedBounds({ |
| 58 | + itemCount: 0, |
| 59 | + itemProps: {}, |
| 60 | + itemSize: 10 |
| 61 | + }); |
| 62 | + |
| 63 | + expect(cachedBounds.size).toBe(0); |
| 64 | + |
| 65 | + expect(() => { |
| 66 | + cachedBounds.get(1); |
| 67 | + }).toThrow("Invalid index 1"); |
6 | 68 | });
|
7 | 69 | });
|
0 commit comments