From a7be93c5386fcb0aaaf8f5fefc07cef6c6c58bd2 Mon Sep 17 00:00:00 2001 From: "S. Elliott Johnson" Date: Mon, 8 Jan 2024 18:20:22 -0700 Subject: [PATCH] feat: More unit tests --- .../svelte/src/internal/client/runtime.js | 8 ++-- .../src/internal/client/runtime.test.ts | 43 +++++++++++++++++++ 2 files changed, 47 insertions(+), 4 deletions(-) create mode 100644 packages/svelte/src/internal/client/runtime.test.ts diff --git a/packages/svelte/src/internal/client/runtime.js b/packages/svelte/src/internal/client/runtime.js index 168f59380b..1570e11d86 100644 --- a/packages/svelte/src/internal/client/runtime.js +++ b/packages/svelte/src/internal/client/runtime.js @@ -1960,16 +1960,16 @@ if (DEV) { } /** - * @template {Iterable} T - * @param {T} iterable - * @returns {{ [P in keyof T]: () => T[P] }} + * @template {unknown} TItems + * @template {Iterable} TIterator + * @param {TIterator} iterable + * @returns {(() => TItems)[]} */ export function thunkspread(iterable) { const thunks = []; for (const item of iterable) { thunks.push(() => item); } - // @ts-expect-error -- for obvious reasons return thunks; } diff --git a/packages/svelte/src/internal/client/runtime.test.ts b/packages/svelte/src/internal/client/runtime.test.ts new file mode 100644 index 0000000000..ecd19102cc --- /dev/null +++ b/packages/svelte/src/internal/client/runtime.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { proxy_rest_array, thunkspread } from '..'; + +describe('thunkspread', () => { + it('makes all of its arguments callable', () => { + const items = [1, 2, 'three', 4, { five: 5 }]; + const thunks = thunkspread(items); + expect(thunks.map((thunk) => thunk())).toEqual(items); + }); + + it('works with iterables', () => { + function* items() { + for (const item of [1, 2, 'three', 4, { five: 5 }]) { + yield item; + } + } + const items_iterator = items(); + const thunks = thunkspread(items_iterator); + expect(thunks.map((thunk) => thunk())).toEqual([...items()]); + }); +}); + +describe('proxy_rest_array', () => { + it('calls its items on access', () => { + const items = [() => 1, () => 2, () => 3]; + const proxied_items = proxy_rest_array(items); + expect(proxied_items[1]).toBe(2); + }); + + it('returns undefined for keys with no item', () => { + const items = [() => 1, () => 2, () => 3]; + const proxied_items = proxy_rest_array(items); + expect(proxied_items[4]).toBe(undefined); + }); + + it('works with array methods', () => { + const items = [() => 1, () => 2, () => 3]; + const proxied_items = proxy_rest_array(items); + expect(proxied_items.map((item) => item)).toEqual([1, 2, 3]); + // @ts-expect-error - This is a weird case for sure + expect(proxied_items.find((item) => item === 1)).toBe(1); + }); +});