From d0282c33354dec701e5de0b4b067f1f9c84ba0a1 Mon Sep 17 00:00:00 2001 From: Alexander Orzechowski Date: Mon, 23 Dec 2024 16:07:50 -0500 Subject: [PATCH] tests: Add tests for duck typing --- tests/duck_typing.test.js | 85 +++++++++++++++++++++++++++++++++++++++ tests/transform.test.js | 1 + 2 files changed, 86 insertions(+) create mode 100644 tests/duck_typing.test.js diff --git a/tests/duck_typing.test.js b/tests/duck_typing.test.js new file mode 100644 index 0000000..03774e7 --- /dev/null +++ b/tests/duck_typing.test.js @@ -0,0 +1,85 @@ +import {test} from 'node:test'; +import assert from 'node:assert'; +import './document.js'; + +import {mount, OArray, Observer} from '../index.js'; + +const createCustomNode = () => { + let elems = []; + let obj = { + elems, + insertBefore: (elem, before) => { + const i = elems.indexOf(before); + if (i === -1) { + elems.push(elem); + } else { + elems.splice(i, 0, elem); + } + }, + replaceChild: (newNode, oldNode) => { + const i = elems.indexOf(oldNode); + elems.splice(i, 1, newNode); + }, + removeChild: (node) => { + const i = elems.indexOf(node); + elems.splice(i, 1); + }, + set textContent (content) { + elems.splice(0, elems.length); + obj.fastClear = true; + }, + get firstChild () { + return elems[0]; + }, + }; + + return obj; +}; + +test("duck type basic", () => { + const elem = createCustomNode(); + + mount(elem, "hello world"); + assert.deepEqual(elem.elems.map(e => e.tree()), ["hello world"]); +}); + +test("duck type basic remove", () => { + const elem = createCustomNode(); + + const remove = mount(elem, "hello world"); + remove(); + + assert.deepEqual(elem.elems.map(e => e.tree()), []); +}); + +test("duck type replace", () => { + const elem = createCustomNode(); + + const obs = Observer.mutable("hello world"); + mount(elem, obs); + obs.set("new"); + + assert.deepEqual(elem.elems.map(e => e.tree()), ["new"]); +}); + +test("duck type array clear", () => { + const elem = createCustomNode(); + + const obs = OArray([1, 2, 3]); + mount(elem, obs); + obs.splice(0, obs.length); + + assert.deepEqual(elem.elems.map(e => e.tree()), []); + assert(elem.fastClear === true) +}); + +test("duck type array nested clear", () => { + const elem = createCustomNode(); + + const obs = OArray([1, 2, 3]); + mount(elem, OArray([obs])); + obs.splice(0, obs.length); + + assert.deepEqual(elem.elems.map(e => e.tree()), []); + assert(elem.fastClear === true) +}); diff --git a/tests/transform.test.js b/tests/transform.test.js index 2be653f..7904acd 100644 --- a/tests/transform.test.js +++ b/tests/transform.test.js @@ -131,6 +131,7 @@ for (const file of files) { 'array.reconciliation.test.js', 'replacement.test.js', 'static.test.js', + 'duck_typing.test.js', ].includes(file)) { describe("iife " + file, transform(file, { assure_import: /^$/,