23
it('should call setCampaignDate on click', function () {
    let spySetCampaign = sinon.spy(wrapper.instance(), 'setCampaignDate');
    let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker);
    assert.equal(datePickers.length, 2);
    console.log(datePickers);
    var date = new Date();

    for (let index = 0; index < datePickers.length; index++) {
      datePickers.simulate('change'); 
      sinon.assert.calledOnce(spySetCampaign.withArgs(date, 'startDate'));
    }


  });

I am trying to simulate my 'change' function and trying to test whether 'setCampaignDate' is called or not. The problem here is that the length of my shallow component returned by find is 2:

let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker);

When trying to call simulate on 'datepickers', it gives an error as below:

'Error: Method “props” is only meant to be run on a single node. 2 found instead.'.

Not sure how to simulate on components having nodes greater than 1.

Sangam Belose
  • 4,262
  • 8
  • 26
  • 48
user3725876
  • 235
  • 1
  • 2
  • 6

4 Answers4

43

The answer for multiple components without changing your code is to use the enzyme API to get the correct index of the button you want.

wrapper.find(Component).at(index).simulate('click');

With component being the name of whatever you're testing and index being the number you want.

Boomer Rogers
  • 965
  • 10
  • 17
11

I think you should add .first().

Something like this:

const selectedCompoent = Wrapper.find(exactlyComponent).first()

In your case:

let datePickers = wrapper.find('.campaign-date-tab').dive().find(Datepicker).first()
Milo
  • 3,365
  • 9
  • 30
  • 44
5

Problem: It means that when you query for '.campaign-date-tab' and 'Datepicker', finder is returning 2 elements. We can't perform any event (like click) at a time on 2 different elements.

Solution: What ever the element that you want to access, make it unique.

Example: set some attribute to identify an element uniquely

<CampaignDateTab class="campaign-date-tab" data-test="dateTab1"/>

And query for it like wrapper.find('[data-test="dateTab1"]')

Again if CampaignDateTab component has multiple Datepicker components. Then you have to differentiate them with some class name or attribute name etc.

You can simulate an event at a time only on one element. Querying for some element should not return multiple elements.

Uday Sravan K
  • 1,305
  • 12
  • 18
0

You are doing a for loop which then uses datePickers (array) instead of the singular datePicker.

You should be able to do:

datePickers[index].simulate('change');

patrick
  • 9,837
  • 3
  • 20
  • 27