react-from-markup
react-from-markup copied to clipboard
Add documentation for testing
There's not much detail given about how both functional and unit testing can be accomplished.
Give some detail about using ReactDOMServer to render statically on-page, and running a rehydrator in a browser-based test environment.
Also give some detail about unit testing strategies for rehydrators.
I've written a lot of these so am happy to add some detail around our current method:
For a rehydrator:
const rehydrator = async (domNode, rehydrateChildren) => {
const props = {
prop1: domNode.getAttribute("data-prop1"),
};
const childrenNode = domNode.querySelector("[data-rehydratable-children]");
const reactifiedChildren = await rehydrateChildren(childrenNode);
return (
<Component {...props}>
{reactifiedChildren}
</Component>
);
};
You could write the following test that would snapshot the props derived at rehydration:
it("Should pass props through correctly on rehydration", async () => {
const component = (
<Component prop1="my Value">
<span>children</span>
</Component>
);
const documentElement = document.createElement("div");
documentElement.innerHTML = ReactDOMServer.renderToStaticMarkup(component);
const rehydrateChildren = jest.fn(() => <span>rehydrated children</span>);
const reactElement = await rehydrator(
documentElement.childNodes[0],
rehydrateChildren
);
expect(reactElement).toMatchSnapshot();
});
There are drawbacks:
- the current method of mocking
rehydrateChildrenis to simplistic and doesn't work well when you have multiplenodeprops. - you need multiple tests in order to spot edge cases, for example, using the above code, having no
childrenin this component will throw an error in the rehydrator aschildrenNodewill be undefined. - being able to reduce the bootstrapping in the tests would help a lot with this being an issue