Skip to content

Commit 4e2eba0

Browse files
Tallybadamdbradley
authored andcommitted
feat(jest): add snapshot serializer (#1570)
1 parent 64953b9 commit 4e2eba0

4 files changed

Lines changed: 60 additions & 1 deletion

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
import { MockNode, serializeNodeToHtml } from '@mock-doc';
3+
4+
const print = (val: HTMLElement | MockNode): string => {
5+
return serializeNodeToHtml(val, {
6+
serializeShadowRoot: true,
7+
prettyHtml: true,
8+
outerHtml: true,
9+
});
10+
};
11+
12+
const test = (val: any): boolean => {
13+
return val !== undefined &&
14+
val !== null &&
15+
(val instanceof HTMLElement || val instanceof MockNode);
16+
};
17+
18+
export const HtmlSerializer = {
19+
print,
20+
test
21+
};

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as d from '../../declarations';
22
import { expectExtend } from '../matchers';
33
import { setupGlobal, teardownGlobal } from '@mock-doc';
44
import { setupMockFetch } from '../mock-fetch';
5-
5+
import { HtmlSerializer } from './jest-serializer';
66

77
declare const global: d.JestEnvironmentGlobal;
88

@@ -11,6 +11,7 @@ export function jestSetupTestFramework() {
1111
global.resourcesUrl = '/build';
1212

1313
expect.extend(expectExtend);
14+
expect.addSnapshotSerializer(HtmlSerializer);
1415

1516
setupGlobal(global);
1617
setupMockFetch(global);
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
// Jest Snapshot v1, https://goo.gl/fbAQLP
2+
3+
exports[`serialize node should serialize 1`] = `
4+
<body>
5+
<div>
6+
Test
7+
</div>
8+
</body>
9+
`;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { HtmlSerializer } from '../jest-serializer';
2+
import { MockDocument } from '@stencil/core/mock-doc';
3+
4+
describe('serialize node', () => {
5+
let doc: MockDocument;
6+
beforeEach(() => {
7+
doc = new MockDocument();
8+
const div = doc.createElement('div');
9+
div.innerText = 'Test';
10+
doc.body.appendChild(div);
11+
});
12+
13+
it('should be valid serializer', () => {
14+
expect(HtmlSerializer.test(doc)).toBeTruthy();
15+
expect(HtmlSerializer.test(doc.body)).toBeTruthy();
16+
});
17+
18+
it('should generate serialized element', () => {
19+
const result = HtmlSerializer.print(doc.body);
20+
expect(result).toContain(`<div>`);
21+
});
22+
23+
it('should serialize', () => {
24+
expect.addSnapshotSerializer(HtmlSerializer);
25+
expect(doc.body).toMatchSnapshot();
26+
});
27+
28+
});

0 commit comments

Comments
 (0)