react-from-markup icon indicating copy to clipboard operation
react-from-markup copied to clipboard

Add documentation for testing

Open simon360 opened this issue 7 years ago • 2 comments

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.

simon360 avatar Sep 25 '18 21:09 simon360

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();
  });

willtonkin avatar Dec 04 '18 15:12 willtonkin

There are drawbacks:

  • the current method of mocking rehydrateChildren is to simplistic and doesn't work well when you have multiple node props.
  • you need multiple tests in order to spot edge cases, for example, using the above code, having no children in this component will throw an error in the rehydrator as childrenNode will be undefined. - being able to reduce the bootstrapping in the tests would help a lot with this being an issue

willtonkin avatar Dec 04 '18 15:12 willtonkin