Skip to content

Commit c3a6f8a

Browse files
author
Tanner Reits
committed
test removeDomNodes()
1 parent f6bb867 commit c3a6f8a

File tree

2 files changed

+45
-5
lines changed

2 files changed

+45
-5
lines changed

src/testing/jest/jest-setup-test-framework.ts

+11-5
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,13 @@ export function jestSetupTestFramework() {
5050
// context so any "cleanup" operations in the `disconnectedCallback`
5151
// can happen to prevent testing errors with async code in the component
5252
//
53-
// We only care about removing all the nodes that are children of the 'body' tag/node
53+
// We only care about removing all the nodes that are children of the 'body' tag/node.
54+
// This node is a child of the `html` tag which is the 2nd child of the document (hence
55+
// the `1` index).
5456
const bodyNode = (
55-
((global as any).window as MockWindow).document as unknown as MockDocument
56-
).childNodes[1].childNodes.find((ref) => ref.nodeName === 'BODY');
57-
bodyNode.childNodes?.forEach(removeDomNodes);
57+
((global as any).window as MockWindow)?.document as unknown as MockDocument
58+
)?.childNodes?.[1]?.childNodes?.find((ref) => ref.nodeName === 'BODY');
59+
bodyNode?.childNodes?.forEach(removeDomNodes);
5860

5961
teardownGlobal(global);
6062
global.Context = {};
@@ -95,7 +97,11 @@ export function jestSetupTestFramework() {
9597
*
9698
* @param node The mocked DOM node that will be removed from the DOM
9799
*/
98-
function removeDomNodes(node: MockNode) {
100+
export function removeDomNodes(node: MockNode) {
101+
if (node == null) {
102+
return;
103+
}
104+
99105
if (!node.childNodes?.length) {
100106
node.remove();
101107
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { MockHTMLElement, MockNode } from '../../../mock-doc/node';
2+
import { removeDomNodes } from '../jest-setup-test-framework';
3+
4+
describe('jest setup test framework', () => {
5+
describe('removeDomNodes', () => {
6+
it('removes all children of the parent node', () => {
7+
const parentNode = new MockHTMLElement(null, 'div');
8+
parentNode.appendChild(new MockHTMLElement(null, 'p'));
9+
10+
expect(parentNode.childNodes.length).toEqual(1);
11+
12+
removeDomNodes(parentNode);
13+
14+
expect(parentNode.childNodes.length).toBe(0);
15+
});
16+
17+
it('does nothing if there is no parent node', () => {
18+
const parentNode: MockNode = undefined;
19+
20+
removeDomNodes(parentNode);
21+
22+
expect(parentNode).toBeUndefined();
23+
});
24+
25+
it.each([null, []])('does nothing if the parent node has no children', (children: MockNode[]) => {
26+
const parentNode = new MockHTMLElement(null, 'div');
27+
parentNode.childNodes = children;
28+
29+
removeDomNodes(parentNode);
30+
31+
expect(parentNode.childNodes).toBe(children);
32+
});
33+
});
34+
});

0 commit comments

Comments
 (0)