mzgoddard / preact-render-spy

Render preact components with access to the produced virtual dom for testing.

Home Page:https://www.npmjs.com/package/preact-render-spy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Handy debug tips

joshuataylor opened this issue · comments

Loving preact-render-spy!

I would like to contribute, and thought maybe we can start brainstorming ideas for developer experience/ergonomics for the wiki, as writing tests can sometimes be a little tricky.

One of the issues that I have is that I want to see the HTML of the component, for development purposes. This would be handy for seeing exactly what the component is outputting.

How would I do this? Something like:

const context = shallow(<Testable />);
console.log(context.output().html())

What other ideas do other folks have?

@joshuataylor Since its preact. You could get the DOM with context.component().base. preact stores the component's dom element at the .base member. You could get the html as a string with context.component().base.outerHTML I think (or .innerHTML if you want that). That'll be up to the support of your DOM environment. (Testing with a browser through selenium, karma, etc, would obviously work. I'd figure jsdom should support that as well, but I don't personally know.)

I think the best place right now for tips like this would be in our examples section or in a related adjacent section.

Currently the noted techniques for what you are asking will work with stateful classes extending Component.

In your usecase, the document fragment we use is stored in context.fragment this should be what you are looking for.

It's undocumented, but that could change.

One thing, with a shallow render, any component/stateless function children will not have any representation in the DOM, we replace them with null nodes during the render, so you won't have any representation of those children in the DOM iteself.

try some of these and let me know if we already have the solution but just need some documentation:

const context = shallow(<Testable />);
console.log(context.fragment);
// we also have our own toString that does a shallow render:
console.log(context.toString());
// if using jest you could even use our snapshot plugin (read docs)
expect(context).toMatchSnapshot();

Sorry for the delay in getting back! Yes, context.fragment is perfect and returns what I need. Will see if I can write some documentation with my experiences, preact-render-spy makes things so much easier.