npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@testing-library/react-render-stream

v1.0.3

Published

## What is this library?

Downloads

2,733

Readme

@testing-library/react-render-stream

What is this library?

This library allows you to make render-per-render asserions on your React components and hooks. This is usually not necessary, but can be highly beneficial when testing hot code paths.

Who is this library for?

This library is intended to test libraries or library-like code. It requires you to write additional components so you can test how your components interact with other components in specific scenarios.

As such, it is not intended to be used for end-to-end testing of your application.

Brought to you by Apollo

This library originally was part of the Apollo Client test suite and is maintained by the Apollo Client team.

Usage examples:

createRenderStream with DOM snapshots

If used with snapshotDOM, RSTL will create a snapshot of your DOM after every render, and you can iterate through all the intermediate states of your DOM at your own pace, independenly of how fast these renders actually happened.

test('iterate through renders with DOM snapshots', async () => {
  const {takeRender, render} = createRenderStream({
    snapshotDOM: true,
  })
  const utils = render(<Counter />)
  const incrementButton = utils.getByText('Increment')
  await userEvent.click(incrementButton)
  await userEvent.click(incrementButton)
  {
    const {withinDOM} = await takeRender()
    const input = withinDOM().getByLabelText('Value')
    expect(input.value).toBe('0')
  }
  {
    const {withinDOM} = await takeRender()
    const input = withinDOM().getByLabelText('Value')
    expect(input.value).toBe('1')
  }
  {
    const {withinDOM} = await takeRender()
    const input = withinDOM().getByLabelText('Value')
    expect(input.value).toBe('2')
  }
})

renderToRenderStream as a shortcut for createRenderStream and calling render

In every place you would call

const renderStream = createRenderStream(options)
const utils = renderStream.render(<Component />, options)

you can also call

const renderStream = renderToRenderStream(<Component />, combinedOptions)
// if required
const utils = await renderStream.renderResultPromise

This might be shorter (especially in cases where you don't need to access utils), but keep in mind that the render is executed asynchronously after calling renderToRenderStream, and that you need to await renderResultPromise if you need access to utils as returned by render.

renderHookToSnapshotStream

Usage is very similar to RTL's renderHook, but you get a snapshotStream object back that you can iterate with takeSnapshot calls.

test('`useQuery` with `skip`', async () => {
  const {takeSnapshot, rerender} = renderHookToSnapshotStream(
    ({skip}) => useQuery(query, {skip}),
    {
      wrapper: ({children}) => <Provider client={client}>{children}</Provider>,
    },
  )

  {
    const result = await takeSnapshot()
    expect(result.loading).toBe(true)
    expect(result.data).toBe(undefined)
  }
  {
    const result = await takeSnapshot()
    expect(result.loading).toBe(false)
    expect(result.data).toEqual({hello: 'world 1'})
  }

  rerender({skip: true})
  {
    const snapshot = await takeSnapshot()
    expect(snapshot.loading).toBe(false)
    expect(snapshot.data).toEqual(undefined)
  }
})

Tracking which components rerender with useTrackRenders

You can track if a component was rerendered during a specific render by calling useTrackRenders within it.

test('`useTrackRenders` with suspense', async () => {
  function ErrorComponent() {
    useTrackRenders()
    // return ...
  }
  function DataComponent() {
    useTrackRenders()
    const data = useSuspenseQuery(someQuery)
    // return ...
  }
  function LoadingComponent() {
    useTrackRenders()
    // return ...
  }
  function App() {
    useTrackRenders()
    return (
      <ErrorBoundary FallbackComponent={ErrorComponent}>
        <React.Suspense fallback={<LoadingComponent />}>
          <DataComponent />
        </React.Suspense>
      </ErrorBoundary>
    )
  }

  const {takeRender, render} = createRenderStream()
  render(<App />)
  {
    const {renderedComponents} = await takeRender()
    expect(renderedComponents).toEqual([App, LoadingComponent])
  }
  {
    const {renderedComponents} = await takeRender()
    expect(renderedComponents).toEqual([DataComponent])
  }
})

[!NOTE]

The order of components in renderedComponents is the order of execution of useLayoutEffect. Keep in mind that this might not be the order you would expect.

taking custom snapshots inside of helper Components with replaceSnapshot

If you need to, you can also take custom snapshots of data in each render.

test('custom snapshots with `replaceSnapshot`', async () => {
  function Counter() {
    const [value, setValue] = React.useState(0)
    replaceSnapshot({value})
    // return ...
  }

  const {takeRender, replaceSnapshot, render} = createRenderStream<{
    value: number
  }>()
  const utils = render(<Counter />)
  const incrementButton = utils.getByText('Increment')
  await userEvent.click(incrementButton)
  {
    const {snapshot} = await takeRender()
    expect(snapshot).toEqual({value: 0})
  }
  {
    const {snapshot} = await takeRender()
    expect(snapshot).toEqual({value: 1})
  }
})

[!TIP]

replaceSnapshot can also be called with a callback that gives you access to the last snapshot value.

[!TIP]

You can also use mergeSnapshot, which shallowly merges the last snapshot with the new one instead of replacing it.

Making assertions directly after a render with onRender

test('assertions in `onRender`', async () => {
  function Counter() {
    const [value, setValue] = React.useState(0)
    replaceSnapshot({value})
    return (
      <CounterForm value={value} onIncrement={() => setValue(v => v + 1)} />
    )
  }

  const {takeRender, replaceSnapshot, renderResultPromise} =
    renderToRenderStream<{
      value: number
    }>({
      onRender(info) {
        // you can use `expect` here
        expect(info.count).toBe(info.snapshot.value + 1)
      },
    })
  const utils = await renderResultPromise
  const incrementButton = utils.getByText('Increment')
  await userEvent.click(incrementButton)
  await userEvent.click(incrementButton)
  await takeRender()
  await takeRender()
  await takeRender()
})

[!NOTE]

info contains the base profiling information passed into onRender of React's Profiler component, as well as snapshot, replaceSnapshot and mergeSnapshot

expect(...)[.not].toRerender() and expect(...)[.not].toRenderExactlyTimes(n)

This library adds to matchers to expect that can be used like

test('basic functionality', async () => {
  const {takeRender} = renderToRenderStream(<RerenderingComponent />)

  await expect(takeRender).toRerender()
  await takeRender()

  // trigger a rerender somehow
  await expect(takeRender).toRerender()
  await takeRender()

  // ensure at the end of a test that no more renders will happen
  await expect(takeRender).not.toRerender()
  await expect(takeRender).toRenderExactlyTimes(2)
})

These matchers can be used on multiple different objects:

await expect(takeRender).toRerender()
await expect(renderStream).toRerender()
await expect(takeSnapshot).toRerender()
await expect(snapshotStream).toRerender()

[!NOTE]

By default, .toRerender and toRenderExactlyTimes will wait 100ms for renders or to ensure no more renders happens.

You can modify that with the timeout option:

await expect(takeRender).not.toRerender({timeout: 300})

[!TIP]

If you don't want these matchers not to be automatically installed, you can import from @testing-library/react-render-stream instead.

A note on act.

You might want to avoid using this library with act, as act can end up batching multiple renders into one in a way that would not happen in a production application.

While that is convenient in a normal test suite, it defeats the purpose of this library.

Keep in mind that tools like userEvent.click use act internally. Many of those calls would only trigger one render anyways, so it can be okay to use them, but avoid this for longer-running actions inside of act calls.