简体   繁体   中英

react-intl onChange testing using enzyme

I have a drop down button component in my react app that lets me change my language

My localeDropDown.js

import React from 'react'
import PropTypes from 'prop-types'
import Cookie from 'js-cookie'

const propTypes = {
  locale: PropTypes.string.isRequired
}

class LocaleDropDown extends React.Component {
  constructor () {
    super()
    this.state = {value: ''}
    this.handleLocaleChange = this.handleLocaleChange.bind(this)
  }

  handleLocaleChange (e) {
    Cookie.set('locale', e.target.value)
    window.location.reload()
  }

  componentDidMount () {
    this.setState({inputValue: Cookie.get('locale')})
  }

  render () {
    return <div>
      <select id="locale-value" onChange={this.handleLocaleChange} value={this.state.inputValue}>
        <option value="en">English</option>
        <option value="fr">French</option>
      </select>
    </div>
  }
}

LocaleDropDown.propTypes = propTypes

export default LocaleDropDown

and my tests are

      const handleLocaleChange = sinon.spy();
      const wrapper = shallow(<LocaleDropDown onChange = {handleLocaleChange}/>)
      const selectInput = wrapper.find("#locale-value")
      selectInput.node.value = 'en'
      wrapper.find('select').simulate('change', selectInput);
      expect(handleLocaleChange.called).toEqual(true)

But it gives me error LocaleDropDown › when simulating a change, handleLocaleChange should be called

TypeError: Cannot add property value, object is not extensible

What am I doing wrong?

A mock event object can be passed along to simulate an event like so:

wrapper.find('select').simulate('change', { target: { value: 'en' } })

More details about the method signature:

.simulate(event[, ...args]) => Self

Simulate events

Arguments

event (String): The event name to be simulated

...args (Any [optional]): A mock event object that will get passed through to the event handlers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM