Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: This method is only meant to be run on single node. 0 found instead. #184

Closed
ninjasort opened this issue Feb 14, 2016 · 61 comments
Closed

Comments

@ninjasort
Copy link

Clearly rendering a node. It's not picking it up..?

render() {
    let groceriesComponents = [],
        newProductInput,
        newProductAddButton,
        clearListButton;

    for(var index = 0; index < this.state.groceries.length; index++) {
      groceriesComponents.push(
          <GroceryListItem
            key={index}
            grocery={this.state.groceries[index]}
          />
      );
    }

    newProductInput = <input className='new-item' type="text" onChange={this.inputChanged}/>;
    newProductAddButton = <button className='add-product' onClick={this.addGroceryItem}>Add new Product</button>;
    clearListButton = <button onClick={this.clearList} className='clear-list'>Clear the List</button>;

    return (
      <div>
        <ul>
          {groceriesComponents}
        </ul>
        {newProductInput}
        {newProductAddButton}
        {clearListButton}
      </div>
    );
  }
}
describe("Task #3 - clearing groceries list", () => {

    beforeEach( () => {
      component = mount(<GroceryListPart3 />);
    });

    it('Should render required tags', () => {
      try { component.find(".clear-list"); }
      catch(err){
        throw new Error("I can't find 'Clear the List' button");
      }
    });

    it('is possible to remove all list items', () => {

      let clearListButton = component.find(".clear-list");
      clearListButton.simulate('click');
      let groceryListItems = component.find("li");

      assert.equal(groceryListItems.length, 0, "There should be exactly zero elements on the groceries list");
    });
  });
Error: This method is only meant to be run on single node. 0 found instead.
@ljharb
Copy link
Member

ljharb commented Feb 14, 2016

Which line does the error come from?

@lelandrichardson
Copy link
Collaborator

lelandrichardson commented Feb 14, 2016

@cameronroe try outputting component.debug() to the console and see if that gives you any clues. From the context you've given us here, I can't see any reason why it would be failing.

@ninjasort
Copy link
Author

Looks like my project was reactjs_koans had duplicate folders and I was editing in the wrong one. No problems. Apologies for that.

@ccorcos
Copy link

ccorcos commented Apr 28, 2016

I still have no idea whats going on here:

Chrome 49.0.2623 (Mac OS X 10.11.3) <Counter /> increments FAILED
    Error: This method is only meant to be run on single node. 0 found instead.
        at ReactWrapper.single (/Users/chetcorcos/code/js-bp/src/test.js:20901:18 <- webpack:///~/enzyme/build/ReactWrapper.js:1099:0)
        at ReactWrapper.simulate (/Users/chetcorcos/code/js-bp/src/test.js:20333:15 <- webpack:///~/enzyme/build/ReactWrapper.js:531:0)
        at Context.<anonymous> (/Users/chetcorcos/code/js-bp/src/test.js:19732:9 <- webpack:///src/ui/counter/test.js:13:54)

@aweary
Copy link
Collaborator

aweary commented Apr 28, 2016

@ccorcos can you share your test case that's throwing this error?

@ccorcos
Copy link

ccorcos commented Apr 28, 2016

figured it out:

    counter.findWhere(node => node.innerText === '+').simulate('click')

we're not in HTML land. I'm just geting the hang of enzyme.

@emragins
Copy link

emragins commented Aug 6, 2016

I get this error with the following in my test, and no header in my component

enzymeWrapper.find('header').hasClass('myClass')

The error happens because no header is found, so hasClass() blows up. I would really appreciate a more meaningful error message that doesn't force me to google it to figure out what the heck it's talking about. That said, now that I understand it, I can understand why this would be difficult to do.......

A start might be instead of "this method" give the name of the method. ie. "'hasClass' is only meant..."

For an uninitiated this would keep from thinking that the it's an internal problem -- my original thought was "oh no... just my luck. Something's going on and one of the internal rendering nodes (processes) can't start up and I have no idea how to debug this".

Another thought is to have find() error if the element(s) can't be found. Since that would break the existing API, and make it so that negative tests would fail, maybe a second parameter of .find(expression, throwOnNotFound) ?

Just throwing out ideas here for discussion.

@ljharb
Copy link
Member

ljharb commented Aug 6, 2016

@emragins is the message "0 found instead" not clear that no header is found?

@emragins
Copy link

emragins commented Aug 6, 2016

It is once I understand the context in which the error is being thrown. I feel like it would be more intuitive if the message were changed to help me find that context by adding the function call in question.

As indicated, I'm very very new to enzyme and my initial reaction to the message was way off-base. I guess my feeling is that with it being a developer tool, any "leg up" to help the developer diagnose the issue is a good thing.

@ljharb
Copy link
Member

ljharb commented Aug 6, 2016

I definitely agree it'd be a great improvement for the error message to contain the method that threw.

@ljharb
Copy link
Member

ljharb commented Aug 6, 2016

@emragins I've added that extra info in 857760c, and it will be included in the next release. Thanks for the suggestion!

@marcfielding1
Copy link

erm what happened to this, I have the same error and it still appears vague?

@ljharb
Copy link
Member

ljharb commented Jul 5, 2017

@jpmelnik @marcfielding1 would you both mind filing separate issues for your problem?

@marcfielding1
Copy link

Yeah sure, actually it's my own fault for being an idiot, I'd refactored some code to the wrapper pattern and was still using shallow().

To be fair I'm not sure what you guys could do about this, the error is actually correct, the problem is if you look at wrapper.html() it actually returns the component it's supposed to - but obviously if I shallow() and then try and work with the values from the sub component it blurts out the error.

I think it's maybe a case of updating the docs to reflect this rather than a bug as such?

Sorry if my comment yesterday was a bit terse I'd been rather rushing around all day :-)

@BennyHinrichs
Copy link

BennyHinrichs commented Feb 8, 2018

I'm getting this same problem. I'm trying to test the onDateChange prop of the react-dates SingleDatePicker, and it thinks I have 0 nodes. Here's an excerpt of my component file:

export default class ExpenseForm extends React.Component {

    onDateChange = (createdAt) => {
        if (createdAt){
            this.setState(() => ({ createdAt }));
        }
    };

    render() {
        return (
            <div>
                <SingleDatePicker 
                    date={this.state.createdAt}
                    onDateChange={this.onDateChange}
                    focused={this.state.calendarFocused}
                    onFocusChange={this.onFocusChange}
                />
            </div>
        )
    }
}

And here's the test:

test('test should set new date on date change', () => {
    const now = moment();
    const wrapper = shallow(<ExpenseForm />);
    wrapper.find('SingleDatePicker').prop('onDateChange')(now);
    expect(wrapper.state('createdAt')).toEqual(now);
});

As the issue title states, it gives me the message, "Method “props” is only meant to be run on a single node. 0 found instead." I feel like I'm following the suggestion you made in Issue #1066, but it's still not working.

Edit: After more testing, this seems to be an issue specific to react-dates. react-dates has three components, DateRangePicker, SingleDatePicker, DayPickerRangeController, and Enzyme doesn't register any of them as nodes. I have no idea what could be behind this issue.

@ljharb
Copy link
Member

ljharb commented Feb 9, 2018

@BennyHinrichs finding with a string is very brittle; in this case, while SingleDatePicker is the identifier you use to import the component, it's not actually the component's display name. Try finding with a reference instead.

@hunterpickett
Copy link

@BennyHinrichs @ljharb

I wasn't sure what you meant by trying to find with a reference instead but after a lot of trial and error / googling around I found out that I could select the element using

  const SDP = wrapper.find('withStyles(SingleDatePicker)');

I found the actual display name by digging through the React Chrome extension and finding out it's exact name.

Though this doesn't seem like a good solution. Have you found a better one?

@revik
Copy link

revik commented May 15, 2018

@BennyHinrichs @sanyangkkun - I believe what @ljharb meant is that instead of using the form -
wrapper.find('SingleDatePicker')
you should remove the quotes (string) and use the component class reference, like so -
wrapper.find(SingleDatePicker);

@romankua
Copy link

Just to add to @revik . SingleDatePicker should be imported as well.

import { SingleDatePicker } from 'react-dates';
//...
wrapper.find(SingleDatePicker);

@chisom5
Copy link

chisom5 commented Jul 11, 2019

please, i am having the same issue, do i need to setup anything before being able to use the simulate method?

@chisom5
Copy link

chisom5 commented Jul 11, 2019

here is my test case :

it("it should call the handleAnswer method correctly", () => {
const handleAnswer = jest.fn();
const wrapper = shallow();
wrapper.find(".badge").simulate("click");
expect(handleAnswer).toHaveBeenCalled();
});

@chisom5
Copy link

chisom5 commented Jul 11, 2019

and here is the error from the terminal:
Method “simulate” is meant to be run on 1 node. 0 found instead.

  21 |     const wrapper = shallow(<Badges />);
  22 | 
> 23 |     wrapper.find("badge").simulate("click");
     |                           ^
  24 |     expect(handleAnswer).toHaveBeenCalled();
  25 |   });
  26 | });

@dori871992
Copy link

@chisom5 "badge" should be an inner element (or component) inside your Badge component, error indicates that it is not finding the element correctly in order to simulate a click on it

@chisom5
Copy link

chisom5 commented Oct 15, 2019

Thanks @dori871992 will check that out

@dobal19
Copy link

dobal19 commented Nov 6, 2019

i am also getting the same problem
test('Change the month to the next month when right icon is clicked on the calendar', () =>{ 83 | wrapper = shallow(<Month month='11' year='2019' />); > 84 | wrapper.find('VS-PullRight VS-Icon').simulate('click'); | ^ 85 | let name = wrapper.find('VS-MonthName').text(); 86 | console.log(name, "month"); 87 | expect(name).toEqual("DECEMBER 2019");
please help

and i am getting the error is
Method “simulate” is meant to be run on 1 node. 0 found instead.

@simoneas02
Copy link

simoneas02 commented Feb 26, 2020

I got the same error Method “props” is meant to be run on 1 node. 0 found instead. and I solved it using withStyles

it("should handle date changes", () => {
    const startDate = moment(0).add(4, "years");
    const endDate = moment(0).add(8, "years");

    wrapper.find("withStyles(DateRangePicker)").prop("onDatesChange")({ startDate, endDate });

    expect(setStartDateSpy).toHaveBeenLastCalledWith(startDate);
    expect(setEndDateSpy).toHaveBeenLastCalledWith(endDate);
  });

@ljharb
Copy link
Member

ljharb commented Feb 27, 2020

@simoneas02 alternatively/better, you could wrapper.find(DateRangePicker) (importing DateRangePicker from react-dates) and do the same.

@MurugarajaRS
Copy link

MurugarajaRS commented Jun 30, 2020

I am also getting error similar to this. Please help me to resolve this.

Test case

describe('Profile Component', () => {
    let wrapper;
    beforeEach(() => {
        wrapper = shallow(<Profile />);
    })       
    it('It should Show the Heading of Profile Component', () => {
        expect(wrapper.find('.heading').render().text()).toEqual("UserProfile");
     }) 
})

Component

import UserApi from "./data/UserApi";
import React from 'react'
import './Profile.css'
import Avatar from '../../img_avatar.png'

export default class Profile extends React.Component {
  constructor(props){
    super(props);
    this.state={
        username:this.props.loggedInUser,
        userDetails:[]
    };
  }
  componentDidMount(){
    UserApi.getUser(this.state.username).then(res => this.setState({userDetails:res.data}));
  }
  
  render() {
    return (
      <div className="root-container">
        <div className="box-container ">
          <form>
              {
                this.state.userDetails && this.state.userDetails.map((value,index)=> {
                  console.log("Index    "+ index)
                  return(
                    <div className="profile" key={value.id}>
                      <div className="center">
                        <span className="heading" >UserProfile</span>
                      </div>
                      <div className='center col-12' >
                        <img src={Avatar} className='avatar' alt="Avatar"></img><br></br>
                      </div>
                      <div className='center'>
                        <label htmlFor="email" className="col-4">First Name</label>
                        <input disabled className="login-input" value={value.firstname}/><br></br>
                      </div>
                      <div className='center'>
                        <label htmlFor="email" className="col-4">Lastname</label>
                        <input disabled className="login-input"  value={value.lastname}/><br></br>
                      </div>
                      <div className='center'>
                        <label htmlFor="email" className="col-4">Email</label>
                        <input disabled className="login-input" value={value.email}/><br></br>
                      </div>
                      <div className='center'>
                        <label htmlFor="email" className="col-4">Location</label>
                        <input disabled className="login-input" value={value.location}/><br></br>
                      </div>
                      <div className='center'>
                        <label htmlFor="email" className='col-4'>Phone</label>
                        <input disabled className="login-input " value={value.phone}/><br></br>
                      </div>
                      <div className='center'>
                        <label htmlFor="email" className='col-4'>Registered Date</label>
                        <input disabled className="login-input " value={value.date +" "+ value.time}/>
                      </div>
                    </div>
                  )
                })
              }
          </form>
        </div>
      </div>
    );
  }
}

Error Getting is

FAIL src/tests/Profile.test.js
● Profile Component › It should Show the Heading of Profile Component

_Method “html” is meant to be run on 1 node. 0 found instead._

  it('It should Show the Heading of Profile Component', () => {
         expect(wrapper.find('.heading').render().text()).toEqual("UserProfile");

@Mercy-1998
Copy link

Mercy-1998 commented Aug 17, 2020

`test('Signned in > new users are redirected', () => {
    const store = mockStore({ user: {loginAction} })
    const redirect = mount(<Provider store={store}><Router history={history}><SignIn/></Router></Provider>)
    expect(redirect.find('Redirect').props()).toHaveProperty('to', '/sign-up')
})`

Do anyone help me on this??

getting error
Method “props” is meant to be run on 1 node. 0 found instead

@ljharb
Copy link
Member

ljharb commented Aug 17, 2020

@Mercy-1998 use the wrappingComponent option to pass Provider - then, what's redirect.debug()?

@Mercy-1998
Copy link

Mercy-1998 commented Aug 17, 2020

` Method “props” is meant to be run on 1 node. 0 found instead.

  56 |         const wrapper = mount(<Provider store={store}><Router history={history}><SignIn/></Router></Provider>)
  57 | 
> 58 |         expect(wrapper.find('Redirect').at(0).props()).toHaveProperty('to', '/sign-up')
     |                                               ^
  59 |     })
  60 | })
  61 | 

`
getting the same @ljharb And Thanks... please help me out

@ljharb
Copy link
Member

ljharb commented Aug 17, 2020

@Mercy-1998 again, change your code so you're passing the Provider via the wrappingComponent option, and then provide the output of wrapper.debug().

@Mercy-1998
Copy link

` Method “props” is meant to be run on 1 node. 0 found instead.

  56 |         const wrapper = mount(<Provider store={store}><Router history={history}><SignIn/></Router></Provider>)
  57 | 
> 58 |         expect(wrapper.find('Redirect').at(0).props()).toHaveProperty('to', '/sign-up')
     |                                               ^
  59 |         console.log(wrapper.debug())
  60 |     })
  61 | })

`
yes done @ljharb

is this right for 'redirect' tag?

@Mercy-1998
Copy link

I got it
by rewriting expect(wrapper.find('Redirect').at(0).props()).toHaveProperty('to', '/sign-up') as expect(wrapper.exists('SignIn')).toBe(true)

@HomyeeKing

This comment has been minimized.

@ljharb

This comment has been minimized.

@HomyeeKing

This comment has been minimized.

@ljharb

This comment has been minimized.

@ljharb

This comment has been minimized.

@HomyeeKing

This comment has been minimized.

@ljharb

This comment has been minimized.

@HomyeeKing

This comment has been minimized.

@ljharb

This comment has been minimized.

@HomyeeKing

This comment has been minimized.

@keithblanchard
Copy link

I started getting this error after I updated react-redux from ^5.0.7 to ^7.2.2. I needed to upgrade so that I could use the functions useSelector, and useDispatch. Does anyone know how this could be related to the version of the library?

@AlbogastAman
Copy link

Any solution for this? Am stuck here too,,wrapper.html() has content but wrapper.find() cant find any elements

@ljharb
Copy link
Member

ljharb commented Feb 24, 2021

@AlbogastAman try .debug() - .html calls cheerio via render, which won’t give you an accurate picture.

@AlbogastAman
Copy link

Thanks for the response @Ijharb,i have tried .debug() but i cant figure out the problem out of .debug() <Connect(ConnectedRouterWithContext) history={{...}}> <Login location={{...}} /> </Connect(ConnectedRouterWithContext)>

@ljharb
Copy link
Member

ljharb commented Feb 25, 2021

Looks like you need at least one .dive() - you need one per HOC.

@BaldeMountaga
Copy link

Good morning everyone I am using jest and enzyme to check the Sign in with exist but I am getting error saying that "Method “text” is meant to be run on 1 node. 0 found instead."

Please I need your helps thank you in advance

describe("Login Page", () => {

it('should render login title', () => {
  const wrapper = shallow (<Login/>);
  const span = wrapper.find('.span.login100-form-title p-b-53');
  const result = span.text();

test1
test2

  expect(result).toBe('Sign In With');
})

}

@BaldeMountaga
Copy link

Note you can omit the image where the describe() method is

@ljharb
Copy link
Member

ljharb commented Sep 26, 2021

Span is a tag name, not a class; remove the leading dot.

@BaldeMountaga
Copy link

Thanks I removed it and put the dot infront and added the class name but still I am having the same error

@BaldeMountaga
Copy link

span tag

@ljharb
Copy link
Member

ljharb commented Sep 27, 2021

You have a space there and “p-b-53” which isn’t a valid tag name. Perhaps that space is meant to be a dot also?

@BaldeMountaga
Copy link

even after removing p-b-53 that is bootstrap part I am still having this " Method “text” is meant to be run on 1 node. 0 found instead."
I am testing a class component is this because I am using a class components?

@ljharb
Copy link
Member

ljharb commented Sep 28, 2021

No, I’m sure it’s another typo. Can you please file a new issue with full component and test code?

@Saifaliabdulhey

This comment was marked as spam.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests