Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
react-test-renderer
Advanced tools
The react-test-renderer package is designed for testing React components in a more efficient and lightweight manner. It provides a renderer that can be used to render React components into pure JavaScript objects without depending on the DOM or a native mobile environment. This makes it ideal for testing components in isolation from the browser or any other external environment.
Rendering components to JSON
This feature allows you to render a React component and generate a JSON output of the rendered component. This is useful for snapshot testing, where you can compare the current version of the component with a previously stored snapshot.
import React from 'react';
import renderer from 'react-test-renderer';
const component = renderer.create(<MyComponent />);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
Testing component output
This feature enables testing of the component's output. You can inspect the rendered component to verify that it has the expected props, state, or behavior. This is useful for ensuring that your component behaves correctly under various conditions.
import React from 'react';
import renderer from 'react-test-renderer';
const component = renderer.create(<MyComponent prop='value' />);
const instance = component.root;
expect(instance.props.prop).toBe('value');
Interacting with component instances
This feature allows you to interact with the component instances directly. You can simulate events or call methods on the component instance and then re-render. This is useful for testing the component's behavior in response to user interactions or lifecycle events.
import React from 'react';
import renderer from 'react-test-renderer';
class MyComponent extends React.Component {
state = { clicked: false };
handleClick = () => {
this.setState({ clicked: true });
};
render() {
return (<button onClick={this.handleClick}>Click me</button>);
}
}
const component = renderer.create(<MyComponent />);
const button = component.root.findByType('button');
button.props.onClick();
expect(component.toJSON()).toMatchSnapshot();
Enzyme is a popular testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output. Unlike react-test-renderer, Enzyme allows you to simulate events and provides a more jQuery-like API for selecting elements. However, it requires an adapter to work with different versions of React.
React Testing Library is a set of helpers that let you test React components without relying on their implementation details. This approach encourages better testing practices by focusing on the behavior of components rather than their internal structure. It's more aligned with user interaction compared to react-test-renderer, which is more about rendering components to JSON for snapshot testing.
react-test-renderer
This package provides an experimental React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
Essentially, this package makes it easy to grab a snapshot of the "DOM tree" rendered by a React DOM or React Native component without using a browser or jsdom.
Documentation:
https://reactjs.org/docs/test-renderer.html
Usage:
const ReactTestRenderer = require('react-test-renderer');
const renderer = ReactTestRenderer.create(
<Link page="https://www.facebook.com/">Facebook</Link>
);
console.log(renderer.toJSON());
// { type: 'a',
// props: { href: 'https://www.facebook.com/' },
// children: [ 'Facebook' ] }
You can also use Jest's snapshot testing feature to automatically save a copy of the JSON tree to a file and check in your tests that it hasn't changed: https://jestjs.io/blog/2016/07/27/jest-14.html.
18.0.0 (March 29, 2022)
Below is a list of all new features, APIs, deprecations, and breaking changes. Read React 18 release post and React 18 upgrade guide for more information.
useId
is a new hook for generating unique IDs on both the client and server, while avoiding hydration mismatches. It is primarily useful for component libraries integrating with accessibility APIs that require unique IDs. This solves an issue that already exists in React 17 and below, but it’s even more important in React 18 because of how the new streaming server renderer delivers HTML out-of-order.startTransition
and useTransition
let you mark some state updates as not urgent. Other state updates are considered urgent by default. React will allow urgent state updates (for example, updating a text input) to interrupt non-urgent state updates (for example, rendering a list of search results).useDeferredValue
lets you defer re-rendering a non-urgent part of the tree. It is similar to debouncing, but has a few advantages compared to it. There is no fixed time delay, so React will attempt the deferred render right after the first render is reflected on the screen. The deferred render is interruptible and doesn't block user input.useSyncExternalStore
is a new hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. It removes the need for useEffect
when implementing subscriptions to external data sources, and is recommended for any library that integrates with state external to React.useInsertionEffect
is a new hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you’ve already built a CSS-in-JS library we don’t expect you to ever use this. This hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout.These new APIs are now exported from react-dom/client
:
createRoot
: New method to create a root to render
or unmount
. Use it instead of ReactDOM.render
. New features in React 18 don't work without it.hydrateRoot
: New method to hydrate a server rendered application. Use it instead of ReactDOM.hydrate
in conjunction with the new React DOM Server APIs. New features in React 18 don't work without it.Both createRoot
and hydrateRoot
accept a new option called onRecoverableError
in case you want to be notified when React recovers from errors during rendering or hydration for logging. By default, React will use reportError
, or console.error
in the older browsers.
These new APIs are now exported from react-dom/server
and have full support for streaming Suspense on the server:
renderToPipeableStream
: for streaming in Node environments.renderToReadableStream
: for modern edge runtime environments, such as Deno and Cloudflare workers.The existing renderToString
method keeps working but is discouraged.
react-dom
: ReactDOM.render
has been deprecated. Using it will warn and run your app in React 17 mode.react-dom
: ReactDOM.hydrate
has been deprecated. Using it will warn and run your app in React 17 mode.react-dom
: ReactDOM.unmountComponentAtNode
has been deprecated.react-dom
: ReactDOM.renderSubtreeIntoContainer
has been deprecated.react-dom/server
: ReactDOMServer.renderToNodeStream
has been deprecated.flushSync
.<Suspense>
boundary in the tree. This ensures the hydrated tree is consistent and avoids potential privacy and security holes that can be caused by hydration mismatches.Promise
, Symbol
, and Object.assign
. If you support older browsers and devices such as Internet Explorer which do not provide modern browser features natively or have non-compliant implementations, consider including a global polyfill in your bundled application.scheduler/tracing
APIundefined
: React no longer throws if you return undefined
from a component. This makes the allowed component return values consistent with values that are allowed in the middle of a component tree. We suggest to use a linter to prevent mistakes like forgetting a return
statement before JSX.act
warnings are now opt-in: If you're running end-to-end tests, the act
warnings are unnecessary. We've introduced an opt-in mechanism so you can enable them only for unit tests where they are useful and beneficial.setState
on unmounted components: Previously, React warned about memory leaks when you call setState
on an unmounted component. This warning was added for subscriptions, but people primarily run into it in scenarios where setting state is fine, and workarounds make the code worse. We've removed this warning.renderToString
: Will no longer error when suspending on the server. Instead, it will emit the fallback HTML for the closest <Suspense>
boundary and then retry rendering the same content on the client. It is still recommended that you switch to a streaming API like renderToPipeableStream
or renderToReadableStream
instead.renderToStaticMarkup
: Will no longer error when suspending on the server. Instead, it will emit the fallback HTML for the closest <Suspense>
boundary and retry rendering on the client.useTransition
and useDeferredValue
to separate urgent updates from transitions. (#10426, #10715, #15593, #15272, #15578, #15769, #17058, #18796, #19121, #19703, #19719, #19724, #20672, #20976 by @acdlite, @lunaruan, @rickhanlonii, and @sebmarkbage)useId
for generating unique IDs. (#17322, #18576, #22644, #22672, #21260 by @acdlite, @lunaruan, and @sebmarkbage)useSyncExternalStore
to help external store libraries integrate with React. (#15022, #18000, #18771, #22211, #22292, #22239, #22347, #23150 by @acdlite, @bvaughn, and @drarmstr)startTransition
as a version of useTransition
without pending feedback. (#19696 by @rickhanlonii)useInsertionEffect
for CSS-in-JS libraries. (#21913 by @rickhanlonii)<StrictMode>
re-run effects to check for restorable state. (#19523 , #21418 by @bvaughn and @lunaruan)object-assign
polyfill. (#23351 by @sebmarkbage)unstable_changedBits
API. (#20953 by @acdlite)useEffect
resulting from discrete events like clicks synchronously. (#21150 by @acdlite)fallback={undefined}
now behaves the same as null
and isn't ignored. (#21854 by @rickhanlonii)lazy()
resolving to the same component equivalent. (#20357 by @sebmarkbage)setImmediate
when available over MessageChannel
. (#20834 by @gaearon)useReducer
observing incorrect props by removing the eager bailout mechanism. (#22445 by @josephsavona)setState
being ignored in Safari when appending iframes. (#23111 by @gaearon)ZonedDateTime
in the tree. (#20617 by @dimaqq)null
in tests. (#22695 by @SimenB)onLoad
not triggering when concurrent features are on. (#23316 by @gnoff)NaN
. (#23333 by @hachibeeDI)package.json
as one of the entry points. (#22954 by @Jack)createRoot
and hydrateRoot
. (#10239, #11225, #12117, #13732, #15502, #15532, #17035, #17165, #20669, #20748, #20888, #21072, #21417, #21652, #21687, #23207, #23385 by @acdlite, @bvaughn, @gaearon, @lunaruan, @rickhanlonii, @trueadm, and @sebmarkbage)aria-description
to the list of known ARIA attributes. (#22142 by @mahyareb)onResize
event to video elements. (#21973 by @rileyjshaw)imageSizes
and imageSrcSet
to known props. (#22550 by @eps1lon)<option>
children if value
is provided. (#21431 by @sebmarkbage)aspectRatio
style not being applied. (#21100 by @gaearon)renderSubtreeIntoContainer
is called. (#23355 by @acdlite)renderToNodeStream
. (#23359 by @sebmarkbage)act
is used in production. (#21686 by @acdlite)global.IS_REACT_ACT_ENVIRONMENT
. (#22561 by @acdlite)act
batch updates. (#21797 by @acdlite)exports
field to package.json
. (#23087 by @otakustay)lazy
support. (#24068 by @gnoff)globalThis
instead of window
for edge environments. (#22777 by @huozhi)FAQs
React package for snapshot testing.
The npm package react-test-renderer receives a total of 4,084,651 weekly downloads. As such, react-test-renderer popularity was classified as popular.
We found that react-test-renderer demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.