Jake Jake - 1 month ago 20
React JSX Question

props.params in Enzyme test

Im trying to test my component that makes a getJSON request in the componentWillMount lifecycle method. It has the following code:

api.getJSON(`users/${this.props.params.id}`)
.done((result) => {
this.setState({user: result});
});


As you can see it uses the props.params.id to make the request. The issue im having is in my test. When I run
npm test
it returns cannot read property of undefined, undefined being the
props.params
. How can I get this object in enzyme?

Answer

This is one way using enzyme with mocha:
- Install jsdom npm install --save-dev --save-exact jsdom jsdom-global
- Load the jsdom on your before statement (inside describe)

    before(function () {
      this.jsdom = require('jsdom-global')()
    })

    after(function () {
      this.jsdom()
    })


- Now in your test use mount like this:

const someData = {data1:'yyyyyy'};
const wrapper = mount(<YourComponent yourProp={someData} />);


In your case "yourProp" should be params, this way you can pass data to your properties.
Hope this help.