question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React Testing Library API types prevent usage of SVG elements

See original GitHub issue
  • @testing-library/react version: 11.1.1
  • Testing Framework and version: jest 25.1.0
  • DOM Environment: jsdom

Relevant code or config:

import * as React from "react";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom/extend-expect";

test("Is a circle", () => {
  const { container } = render(
    <circle cx=0 cy=0 />,
    {
      container:
        document.body.appendChild(
          document.createElementNS("http://www.w3.org/2000/svg", "svg")),
    });

  expect(container.firstChild.nodeName).toBe("circle");
});

What you did:

Trying to set SVG as the container element for testing SVG React components.

What happened:

Typescript threw a type error stating that render() requires an HTMLElement.

Reproduction:

I created a repository illustrating my problem.

Problem description:

React allows components to use HTML and SVG tags. SVG tags do not work properly in an HTML context, and consequently must be rendered inside an SVG context. This can be only done by using an SVG tag as the containing element. Since the API’s types disallow this, users have to wrap all their SVG based components in SVG tags manually and introducing unnecessary nesting to the render output.

Suggested solution:

Propose the following patch to @testing-library/react/types/index.d.ts:

// TypeScript Version: 3.8

import {OptionsReceived as PrettyFormatOptions} from 'pretty-format'
import {queries, Queries, BoundFunction} from '@testing-library/dom'
import {act as reactAct} from 'react-dom/test-utils'

export * from '@testing-library/dom'

type DOMElement = HTMLElement | SVGElement;

export type RenderResult<Q extends Queries = typeof queries> = {
  container: DOMElement
  baseElement: DOMElement
  debug: (
    baseElement?:
      | DOMElement
      | DocumentFragment
      | Array<DOMElement | DocumentFragment>,
    maxLength?: number,
    options?: PrettyFormatOptions,
  ) => void
  rerender: (ui: React.ReactElement) => void
  unmount: () => boolean
  asFragment: () => DocumentFragment
} & {[P in keyof Q]: BoundFunction<Q[P]>}

export interface RenderOptions<Q extends Queries = typeof queries> {
  container?: DOMElement
  baseElement?: DOMElement
  hydrate?: boolean
  queries?: Q
  wrapper?: React.ComponentType
}

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>

/**
 * Render into a container which is appended to document.body. It should be used with cleanup.
 */
export function render(
  ui: React.ReactElement,
  options?: Omit<RenderOptions, 'queries'>,
): RenderResult
export function render<Q extends Queries>(
  ui: React.ReactElement,
  options: RenderOptions<Q>,
): RenderResult<Q>

/**
 * Unmounts React trees that were mounted with render.
 */
export function cleanup(): void

/**
 * Simply calls ReactDOMTestUtils.act(cb)
 * If that's not available (older version of react) then it
 * simply calls the given callback immediately
 */
export const act: typeof reactAct extends undefined
  ? (callback: () => void) => void
  : typeof reactAct

I’ve implemented this patch locally in my project where I discovered the bug and it solves the issue. However, I’m having difficulty committing my patch to react-testing-library due to dtslint commit hook rejecting the types in the React dependency.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:15 (10 by maintainers)

github_iconTop GitHub Comments

2reactions
kentcdoddscommented, Nov 18, 2020

Commit with --no-verify to skip the git hook so you can at least push and we’ll see what’s up on CI.

1reaction
eps1loncommented, Nov 30, 2020

Retrospectively, should this have been a major version bump?

We consider this a bugfix hence the SemVer patch. These can be considered breaking changes in dependent code but that means the dependent code relied on a bug.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Common mistakes with React Testing Library - Kent C. Dodds
Hi there I created React Testing Library because I wasn't satisfied with the testing landscape at the time. It expanded to DOM Testing ......
Read more >
Considerations for fireEvent | Testing Library
This works properly for most situations when you simply want to test what happens when your element is clicked, but when the user...
Read more >
Testing a simple component with React Testing Library
In this post join me as I use React Testing Library to test a simple React component. Apart from applying the testing library...
Read more >
Test correct SVG component renders with jest and react ...
Initially, I want the MaleAvatar svg to render and then if the value of gender is changed to false the FemaleAvatar svg renders...
Read more >
Test your React components and APIs with React Testing ...
Testing our UI components and API requests, using React Testing Library, Jest and Ts-Jest. And, of course, we`ll be using Typescript.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found