import { beforeEach, describe, expect, test, vi } from 'vitest' import { installTranslationDomGuard, resetTranslationDomGuardForTests, type NodeLike, } from './translation-dom-guard' type FakeNode = { parentNode: FakeNode | null } type FakeProto = { removeChild: { call: (self: FakeNode, child: FakeNode) => unknown } insertBefore: { call: (self: FakeNode, node: FakeNode, ref: FakeNode | null) => unknown } } function setup({ isTranslated }: { isTranslated: boolean }) { const nativeRemoveChild = vi.fn((child: FakeNode) => child) const nativeInsertBefore = vi.fn((node: FakeNode) => node) const nodeConstructor = { prototype: { removeChild: nativeRemoveChild, insertBefore: nativeInsertBefore }, } installTranslationDomGuard({ nodeConstructor: nodeConstructor as unknown as NodeLike, isTranslated: () => isTranslated, }) const proto = nodeConstructor.prototype as unknown as FakeProto return { proto, nativeRemoveChild, nativeInsertBefore } } describe('installTranslationDomGuard', () => { beforeEach(() => { resetTranslationDomGuardForTests() }) test('skips removeChild for a detached node on a translated page', () => { const { proto, nativeRemoveChild } = setup({ isTranslated: true }) const parent: FakeNode = { parentNode: null } const child: FakeNode = { parentNode: { parentNode: null } } expect(proto.removeChild.call(parent, child)).toBe(child) expect(nativeRemoveChild).not.toHaveBeenCalled() }) test('appends instead of dropping the node when the reference node is detached', () => { const { proto, nativeInsertBefore } = setup({ isTranslated: true }) const parent: FakeNode = { parentNode: null } const newNode: FakeNode = { parentNode: null } const reference: FakeNode = { parentNode: { parentNode: null } } proto.insertBefore.call(parent, newNode, reference) expect(nativeInsertBefore).toHaveBeenCalledWith(newNode, null) }) test('leaves the native error in place on an untranslated page', () => { const { proto, nativeRemoveChild, nativeInsertBefore } = setup({ isTranslated: false }) const parent: FakeNode = { parentNode: null } const orphan: FakeNode = { parentNode: { parentNode: null } } proto.removeChild.call(parent, orphan) proto.insertBefore.call(parent, { parentNode: null }, orphan) expect(nativeRemoveChild).toHaveBeenCalledWith(orphan) expect(nativeInsertBefore).toHaveBeenCalledWith(expect.anything(), orphan) }) test('passes valid calls through untouched, including a null reference node', () => { const { proto, nativeRemoveChild, nativeInsertBefore } = setup({ isTranslated: true }) const parent: FakeNode = { parentNode: null } const child: FakeNode = { parentNode: parent } const newNode: FakeNode = { parentNode: null } proto.removeChild.call(parent, child) proto.insertBefore.call(parent, newNode, child) proto.insertBefore.call(parent, newNode, null) expect(nativeRemoveChild).toHaveBeenCalledWith(child) expect(nativeInsertBefore).toHaveBeenNthCalledWith(1, newNode, child) expect(nativeInsertBefore).toHaveBeenNthCalledWith(2, newNode, null) }) })