I
I
Igor Shumilovsky2015-11-16 16:25:12
JavaScript
Igor Shumilovsky, 2015-11-16 16:25:12

Why doesn't Simulate.click fire in TestUtils?

I'm playing with tests (karma, mocha, chai) and can't figure out why click emulation doesn't work. What am I doing wrong?
Test:

import React from 'react'
import TestUtils from 'react-addons-test-utils'

import Home from '../app/views/home/home'

describe('home page', () => {
  let home

  beforeEach(() => {
    home = TestUtils.renderIntoDocument(<Home />)
  })

  it('should be abble to hide the content by clicking', () => {
    let title = TestUtils.scryRenderedDOMComponentsWithClass(home, 'title')
    TestUtils.Simulate.click(home)
    expect(title.length).to.equal(0)
  })
})

Component:
import React, { Component } from 'react'

class Home extends Component {
  constructor (props) {
    super(props)
    this.state = {
      show: true
    }
  }

  handleClick () {
    this.setState({
      show: !this.state.show
    })
  }

  render () {
    let getTitle = () => {
      return this.state.show ? (
        <h1 className='title'>Home page</h1>
      ) : ''
    }
    return (
      <div className='page' onClick={this.handleClick}>
        {getTitle()}
      </div>
    )
  }
}

export default Home

Click should render | don't render title by state state. In short, after the click, title.length should become 0, but it remains 1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Shumilovsky, 2015-11-16
@JiSeven

Found errors. The click does not work, because you need to "click" on the node, and not on the composite component. Because this code:

let title = TestUtils.scryRenderedDOMComponentsWithClass(home, 'title')
    TestUtils.Simulate.click(home)
    expect(title.length).to.equal(0)

should be replaced with:
let homeNode = TestUtils.findRenderedDOMComponentWithTag(home, 'div')
    TestUtils.Simulate.click(homeNode)
    title = TestUtils.scryRenderedDOMComponentsWithClass(home, 'title')
    expect(title.length).to.equal(0)

Then the click will work.
PS I made a mistake in the component - I forgot to put bind on the handleClick function
<div className='page' onClick={this.handleClick.bind(this)}>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question