73 lines
2.4 KiB
JavaScript
73 lines
2.4 KiB
JavaScript
// Component behavior in both worlds: plain string rendering without a DOM,
|
|||
|
|
// and mount/update/morph/proxy semantics inside happy-dom.
|
||
|
|
|
||
|
|
import { test, before } from 'node:test'
|
||
|
|
import assert from 'node:assert'
|
||
|
|
import { Window } from 'happy-dom'
|
||
|
|
|
||
|
|
import serverHtml from '@choojs/html/server'
|
||
|
|
|
||
|
|
test('renders via createElement on the server (no window)', async () => {
|
||
|
|
const { default: Component } = await import('../index.js')
|
||
|
|
|
||
|
|
class Title extends Component {
|
||
|
|
createElement (text) {
|
||
|
|
return serverHtml`<h1>${text}</h1>`
|
||
|
|
}
|
||
|
|
|
||
|
|
update () { return false }
|
||
|
|
}
|
||
|
|
|
||
|
|
const res = new Title().render('hello')
|
||
|
|
assert.strictEqual(res.toString(), '<h1>hello</h1>')
|
||
|
|
})
|
||
|
|
|
||
|
|
test('browser: render, mount, update morphs in place, proxy stands in', async () => {
|
||
|
|
const win = new Window()
|
||
|
|
globalThis.window = win
|
||
|
|
globalThis.document = win.document
|
||
|
|
// module registry caches per specifier; component/index.js re-evaluates
|
||
|
|
// _hasWindow per instance, so importing after globals are set is enough
|
||
|
|
const { default: Component } = await import('../index.js?browser')
|
||
|
|
const { default: html } = await import('@choojs/html/browser')
|
||
|
|
const { default: morph } = await import('@choojs/html/morph')
|
||
|
|
|
||
|
|
class Counter extends Component {
|
||
|
|
createElement (n) {
|
||
|
|
this.n = n
|
||
|
|
return html`<div>count ${n}</div>`
|
||
|
|
}
|
||
|
|
|
||
|
|
update (n) {
|
||
|
|
return n !== this.n
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
const counter = new Counter('counter')
|
||
|
|
|
||
|
|
const el = counter.render(0)
|
||
|
|
assert.ok(el.getAttribute('data-nanocomponent'), 'root node branded')
|
||
|
|
document.body.appendChild(el)
|
||
|
|
assert.strictEqual(counter.element, el, 'element getter finds mounted node')
|
||
|
|
|
||
|
|
// unchanged args: update() false, no morph, proxy returned
|
||
|
|
const proxy = counter.render(0)
|
||
|
|
assert.ok(proxy.hasAttribute('data-proxy'), 'returns proxy while mounted')
|
||
|
|
assert.ok(proxy.isSameNode(el), 'proxy claims identity of the mounted node')
|
||
|
|
|
||
|
|
// changed args: update() true, mounted node morphs in place
|
||
|
|
counter.render(1)
|
||
|
|
assert.strictEqual(el.textContent, 'count 1', 'mounted node updated in place')
|
||
|
|
|
||
|
|
// and the proxy plays correctly with nanomorph in a parent view
|
||
|
|
const parent = (n) => {
|
||
|
|
const inner = counter.render(n)
|
||
|
|
return html`<main>${inner}</main>`
|
||
|
|
}
|
||
|
|
const treeA = parent(1)
|
||
|
|
// simulate first full-page render: mounted component moves into the tree
|
||
|
|
assert.ok(treeA.querySelector('[data-proxy]') || treeA.contains(el))
|
||
|
|
|
||
|
|
document.body.removeChild(el)
|
||
|
|
})
|