3

I have a component that trigger re-rendering when I call setState() in componentDidMount(). Here is sample code:

import React from 'react'

class MyComponent extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      message: 'Hello'
    }
  }

  componentDidMount () {
    this.fetchMessage().then((message) => {
      this.setState({ message })
    })
  }

  fetchMessage() {
    return Promise.resolve('World')
  }

  render() {
    return this.state.message
  }
}

and my test is like this:

import MyComponent from './MyComponent'
import { shallow } from 'enzyme'

describe('<MyComponent>', () => {
  it('renders World', () => {
    const wrapper = shallow(<MyComponent />)
    expect(wrapper.text()).toEqual('World') # => results shows Hello
  })
})

Please note, I am using enzyme to assist with my test.

The test failed because the returned results is Hello which is the initial rendering.

So my question here is what's the way to ensure that the re-rendering has triggered before carrying out the assertion?

1
  • You need to use mount and not shallow
    – klugjo
    Dec 21, 2017 at 2:51

1 Answer 1

0

Hellow,

You have to use mount if you want to test lifeCycleMethod.

Note that setState is async, so if this.fetchMessage take time, you will find yourself into a beautiful race condition on your render and in your test.

To avoid this, try to extract the render into a stateless function.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.