/* eslint-env jest */
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
import React, { act } from 'react';
import { createRoot } from 'react-dom/client';
import { renderToStaticMarkup, renderToString } from 'react-dom/server';
import renderer from 'react-test-renderer';
import { render } from '@testing-library/react';
import snapshot from 'jest-snapshot';
import diff from 'jest-diff';
import { html, oneLineTrim } from 'common-tags';
import htmrServer from '../src';
import htmrBrowser from '../src/index.browser';
describe('core', () => {
test('it works', () => {
testRender('
This is cool
');
});
// https://github.com/pveyes/htmr/issues/156
test('does not set generic key on a single root node', () => {
['', 'a
', 'ab
'].forEach(
(fixture) => {
const nodes = [htmrServer(fixture), htmrBrowser(fixture)];
nodes.forEach((node) => {
const root = Array.isArray(node) ? node.filter(Boolean)[0] : node;
expect(root.key).not.toBe('0');
});
}
);
expect(htmrServer('').key).toBeNull();
expect(htmrBrowser('').key).toBeNull();
});
test('keeps keys on multiple root nodes', () => {
[htmrServer, htmrBrowser].forEach((htmr) => {
expect(htmr('a
b
').map((n) => n.key)).toEqual(['0', '1']);
});
});
test('throws if first argument is not a string', () => {
const error = new Error('Expected HTML string');
const fixtures = [null, [], {}, 1, true];
// server & browser
expect.assertions(fixtures.length * 2);
fixtures.forEach((fixture) => {
expect(() => htmrServer(fixture)).toThrow(error);
expect(() => htmrBrowser(fixture)).toThrow(error);
});
});
test('can render self closing component', () => {
testRender(' ');
testRender(' ');
testRender(' ');
});
test('can render sibling element as multiple children', () => {
testRender('Multi
Component
');
});
test('can render element inside text node', () => {
testRender('what are you doing?');
});
test('ignore comment', () => {
testRender('no comment
');
});
test('ignore multiline comment', () => {
testRender(oneLineTrim`
no multiline comment
`);
});
});
describe('attributes', () => {
test('correctly map HTML attributes to react props', () => {
testRender(' ');
testRender(
'
'
);
testRender(' ');
testRender(oneLineTrim`
`);
testRender(' ');
testRender('');
testRender(
' '
);
testRender('Stress reliever ');
testRender('July 7 ');
testRender(' ');
testRender(html`
Avatar
`);
});
// https://github.com/pveyes/htmr/issues/103
test('correctly handle boolean attributes', () => {
const { container } = render(htmrBrowser(''));
expect(container.querySelector('iframe').allowFullscreen).toBe(true);
});
// https://github.com/pveyes/htmr/issues/137
test('pass non-boolean attributes as is', () => {
const { container } = render(htmrBrowser(' '));
expect(container.querySelector('img').alt).toEqual('alt');
expect(container.querySelector('img').className).toEqual('');
});
test('correctly convert multiple style values', () => {
testRender('');
testRender(' ');
testRender(
'
'
);
});
test('can handle css vendor prefixes', () => {
testRender(
'prefix '
);
});
test('decode HTML entities inside style declaration', () => {
testRender(
' '
);
});
test('ignore invalid style', () => {
testRender('Explore Categories
');
testRender('Explore Categories
');
});
test('handle CSS custom properties correctly', () => {
testRender('Explore Categories
');
testRender(
'Explore Categories
'
);
});
});
describe('encoding', () => {
test('unescape html entities', () => {
testRender('& and & ');
});
test('decode html entities on defaultMap', () => {
testRender('& and &
', {
transform: {
_: (node, props, children) => {
if (typeof props === 'undefined') {
return node;
}
return {children}
;
},
},
});
});
test('decode html attributes', () => {
testRender('test ');
});
test('dangerously rendered script tag is not encoded', () => {
const html = `
`.trim();
testRender(html, { dangerouslySetChildren: ['script'] });
});
});
describe('options', () => {
describe('transform', () => {
test('custom component', () => {
const Section = (props) => {
const { children, 'data-heading': heading, ...rest } = props;
return (
);
};
testRender(
'Custom component
',
{ transform: { p: Section } }
);
});
test('default mapping', () => {
let i = 0;
const defaultMap = (node, props, children) => {
if (typeof props === 'undefined') {
// we need to add key for elements inside array
return {node} ;
}
return {children}
;
};
testRender('Default mapping
', {
transform: { _: defaultMap },
});
});
});
describe('preserveAttributes', () => {
test('allow preserve some attributes', () => {
testRender(
html`
`,
{ preserveAttributes: ['ng-if', new RegExp('tv-')] }
);
});
});
describe('dangerouslySetChildren', () => {
test('preserve the content of style tag by default', () => {
testRender(oneLineTrim`
`);
});
test('should dangerously set html for required tags', () => {
const html = oneLineTrim`
<a href="/">Test</a>
`;
testRender(html, { dangerouslySetChildren: ['pre'] });
});
test('no dangerously render script tag', () => {
testRender(html`
`);
});
test('dangerously render empty script tag', () => {
testRender('', {
dangerouslySetChildren: ['script'],
});
});
});
});
describe('whitespace', () => {
test('allow whitespace only text nodes between elements', () => {
testRender('Hello World ');
});
test('allow newline only text node between elements', () => {
testRender('Hello \nWorld ');
});
test('remove whitespace on table elements', () => {
testRender(html`
`);
});
});
expect.extend({
toRenderConsistently({ server, browser }, html) {
const serverRender = create(server);
const browserRender = create(browser);
const serverHtml = snapshot.utils.serialize(serverRender);
const browserHtml = snapshot.utils.serialize(browserRender);
const diffString = diff(serverHtml, browserHtml, {
expand: this.expand,
aAnnotation: 'Server render',
bAnnotation: 'Browser render',
});
const pass = serverHtml === browserHtml;
let messageExpectation;
if (pass) {
messageExpectation =
'Expected server rendered HTML to not equal browser rendered HTML';
} else {
messageExpectation =
'Expected server rendered HTML to equal browser rendered HTML';
}
const message = () =>
messageExpectation +
'\n\n' +
'Server render:\n' +
` ${this.utils.printExpected(serverHtml)} \n` +
'Browser render:\n' +
` ${this.utils.printReceived(browserHtml)} \n` +
(diffString ? `\n\nDifference: \n\n${diffString} ` : '');
return { message, pass };
},
});
/**
* Test utilities
*/
// react-test-renderer renders asynchronously on React 18+ unless wrapped in act
function create(element) {
let root;
act(() => {
root = renderer.create(element);
});
return root;
}
function testRender(html, options) {
const server = htmrServer(html, options);
const browser = htmrBrowser(html, options);
expect({ server, browser }).toRenderConsistently(html);
// assert SSR
expect(() => renderToString(server)).not.toThrow();
expect(() => renderToStaticMarkup(server)).not.toThrow();
// assert CSR
const el = document.createElement('div');
try {
document.body.appendChild(el);
expect(() => {
act(() => {
createRoot(el).render(browser);
});
}).not.toThrow();
} finally {
document.body.removeChild(el);
}
// assert snapshot, doesn't matter from server or browser
// because we've already done assert equal between them
expect(create(server)).toMatchSnapshot();
}