Forbes magazine logo Ranked Best Coding Bootcamps 2023

Jest test React stateless functions

Altcademy Team wrote on 7 February 2018

When testing a React stateless function, Jest can't use findDOMNode to find the component.
Because stateless functions don't have a backing instance, you can't attach a ref to a stateless function component. Normally this isn't an issue, since stateless functions do not provide an imperative API. Without an imperative API, there isn't much you could do with an instance anyway. However, if a user wants to find the DOM node of a stateless function component, they must wrap the component in a stateful component (eg. ES6 class component) and attach the ref to the stateful wrapper component.
According to http://t4d.io/jest-testutils-and-react-stateless-components/

You can wrap the stateless function Component in a div tag so the DOM node can be found.

beforeEach(() => { component = TestUtils.renderIntoDocument(<div><RenderDemo /></div>); }); it('<RenderDemo /> renders', () => { expect(ReactDOM.findDOMNode(component).querySelector('h1').textContent) .toBe('Hello World!'); });

Trusted by

Students and instructors from world-class organizations

Imperial College London
Carnegie Mellon University
City University of Hong Kong
Hack Reactor
Cisco Meraki
University of Oxford
Swift
Bazaarvoice
Waterloo
Uber
AtlanTech
Tumblr
Boston College
Bombardier Aerospace
University of St. Andrews
New York University
Minerva Schools at KGI
Merrill Lynch
Riot Games
JP Morgan
Morgan Stanley
Advanced Placement®
Google
KPMG
The University of Hong Kong
University of Toronto
SCMP
Moat
Zynga
Hello Toby
Deloitte
Goldman Sachs
Yahoo
HSBC
General Assembly
Tesla
McGill University
Microsoft

Join the upcoming Cohort #97

Enroll for January 6th, 2025