0

Using Mocha, Karma, and React test tools to test the following simple function:

renderTodoCount() {
    const { incompleteCount } = this.props;
    const itemWord = incompleteCount === 1 ? 'item' : 'items';

    return (
      <span className='todo-count'>
        <strong>{incompleteCount || 'No'}</strong> {itemWord} left
      </span>
    );
}

I'm splitting the test cases up into three cases: 1. incompleteCount=0, 2. incompleteCount=1, 3. incompleteCount=2.

In the first case, I would expect the following output (more or less):

  <span className='todo-count'>
    <strong>No</strong> items left
  </span>

and would test against that. What I am actually seeing(from dump()) is:

  <span class="todo-count" data-reactid=".0.0">
    <strong data-reactid=".0.0.0">No</strong><span data-reactid=".0.0.1"></span><span data-reactid=".0.0.2">items</span><span data-reactid=".0.0.3"> left</span>
 </span>

Is there a good way to test the value of the text inside of the main span? I'm looking for something equivalent to .val() or .text() in jQuery.

4
  • 1
    TestUtils.findRenderedDOMComponentWithClass('todo-count').getDOMNode().textContent Commented Sep 15, 2015 at 6:02
  • That did it! Thanks! Commented Sep 15, 2015 at 6:15
  • 1
    Not related to your question, but to do conditional plurals you should do const itemWord = incompleteCount !== 0 ? 'item' : 'items'; Commented Sep 15, 2015 at 7:18
  • interesting, I grabbed that part of the code from a tutorial. why is this? Commented Sep 16, 2015 at 7:59

1 Answer 1

1

By using the TestUtils that comes bundled with React you can extract the actual DOM node and use the .textContent property in order to get the text.

TestUtils.findRenderedDOMComponentWithClass('todo-count').getDOMNode().textCont‌​ent
Sign up to request clarification or add additional context in comments.

2 Comments

getDOMNode has been deprecated btw. It's not React.findDOMNode(component)
Right you are, sir! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.