You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Shallow rendering and parameter object serialization #256
We're currently working on creating unit tests and as a starter, we're trying to snapshot the components using renderToString with shallow set to true.
The problem is that a object passed as parameter to a child component will be rendered as string "[object Object]", simplified example:
As far as I can trace it, it's because the default JS serializing is used for a simple JS object (done in src/util.js -> encodeEntities). We're using typescript and got the parameter typed, but that doesn't help us because I don't think you can override the toString method for that one. Changing everything to classes / functions and override the toString is really a no-go because it adds tons of extra code. Any way provide a callback or something that objects are serialized with (for example) JSON.stringify so we get something like:
Note: I really want to test using the renderToString function and not enzyme or any other jest snapshot serializer, because that just doesn't render the components in exactly the same way this module does.
It would be nice if we have a bit more control over that, so maybe we could pass in a function to the options which will be used instead of the default toString function for the object.
We could change those lines into something like:
if (opts.shallow
&& typeof v === 'object'
&& typeof opts.shallowObjectsToString === 'function'
) {
s = s + ` ${name}="${encodeEntities(opts.shallowObjectsToString(name, v) +'')}"`;
} else {
s = s + ` ${name}="${encodeEntities(v + '')}"`;
}
And we can pass in an option 'shallowObjectsToString' to do whatever we want with it, for example:
Activity
remko79 commentedon May 13, 2023
After finally diving further into this, the "problem" occurs when we typecast the value to a string:
s = s + ` ${name}="${encodeEntities(v + '')}"`;See: https://github.com/preactjs/preact-render-to-string/blob/master/src/pretty.js#L304
It would be nice if we have a bit more control over that, so maybe we could pass in a function to the options which will be used instead of the default toString function for the object.
We could change those lines into something like:
And we can pass in an option 'shallowObjectsToString' to do whatever we want with it, for example:
shallowObjectsToString: (name, v) => JSON.stringify(v),Note that I've added the 'name' to the function so you could do different things depending on the object's name
TechQuery commentedon Nov 21, 2025
@remko79 @JoviDeCroock @rschristian We may use
.toJSON()to handle JSON props value:which is easy for users to hook:
and make SSR compatible with complex Web components, such as https://github.com/idea2app/ECharts-JSX