enzymejs / enzyme

JavaScript Testing utilities for React
https://enzymejs.github.io/enzyme/
MIT License
19.95k stars 2.01k forks source link

How to call `setProps` on a component that returns an array of elements? #2461

Closed rafaeleyng closed 1 year ago

rafaeleyng commented 4 years ago

Hi there

I'm testing a component that does more or less this (the point is that it returns an array of elements, without a wrapper):

const ComponentA = () => {
  return [<div>A</div>, <div>B</div>]
}

In the test I need to change a prop:

const component = shallow(<ComponentA />)
component.setProps({ anything: 0 })

That gives me: Method “rerender” is meant to be run on 1 node. 2 found instead.

I can't add a wrapping <div> in this case.

I've tried with fragments following this SO question (check the comments in the question), and it did not work:

const ComponentA = () => {
  return <><div>A</div><div>B</div></>
}

I've seen the note NOTE: can only be called on a wrapper instance that is also the root instance. on the docs. Not sure what the "root instance" means since the meaning of "instance" seems do be a bit vague there (to my understanding), by I assume it means that I need to have a single component that is the root of a structure.

How can I solve this in my particular scenario? How can I use setProps (or some equivalent solution) with a component that returns an array of elements?


I'm actually using Preact and I'm not sure if this behaviour is exclusive to Preact. My versions are:

enzyme-adapter-preact-pure@2.2.3
enzyme@3.11.0
jest-enzyme@7.1.2
preact@^10.4.8
rafaeleyng commented 4 years ago

Edit: added the link for the related docs

ljharb commented 4 years ago

When you shallow render, the wrapper is the things that it renders - in your case, an array. Why do you need to set the props on <ComponentA /> when you literally just typed that into your test?