simon360 / react-from-markup

Declare your React components with static HTML
MIT License
18 stars 4 forks source link

Add documentation for testing #22

Open simon360 opened 6 years ago

simon360 commented 6 years ago

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.

willtonkin commented 5 years ago

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 commented 5 years ago

There are drawbacks: