enzyme icon indicating copy to clipboard operation
enzyme copied to clipboard

Testing component methods

Open mxstbr opened this issue 10 years ago • 62 comments

I couldn't find any information on this, if this is a duplicate excuse me for stealing your time.

I'm trying to test this application, but I ran into a wall when testing component methods. As an example, take this component:

class Button extends React.Component {
  handleClick() {
    // Do something here
  }
  render() {
    // Component here
  }
}

How could I test the handleClick method here when shallowly rendering this component? (The same question applies to lifecycle methods)

mxstbr avatar Feb 22 '16 18:02 mxstbr

@mxstbr const wrapper = shallow(<Button />); wrapper.instance().handleClick()

ljharb avatar Feb 22 '16 18:02 ljharb

That is so nice, thanks for the fast response @ljharb!

mxstbr avatar Feb 22 '16 19:02 mxstbr

Dumb question: is there a new way to do this? When I call shallow(<MyComponent/>) the thing that gets returned has no "instance` method; instead it looks like this:

{ '$$typeof': Symbol(react.element),
  type: 'div',
  key: null,
  ref: null,
  props: { className: 'fool', children: [ [Object], [Object] ] },
  _owner: null,
  _store: {} }

machineghost avatar Jul 30 '16 00:07 machineghost

@machineghost that's the console inspection which shows enumerable properties. Try actually checking .instance on it.

ljharb avatar Jul 30 '16 00:07 ljharb

Thanks for the quick response, but it's not there for me. I get this:

TypeError: choices.instance is not a function

The real code is something like:

let Choices = React.createClass({
    _buildChoices() { ....}
    ....
}
choices = shallowRender(<Choices step={5}/>);
var buttons = choices.instance()._buildChoices();
// get the above error

P.S. I know the message says it's not a function (implying that it might be an object or something), but if I console.log(choices.instance) it's undefined.

machineghost avatar Jul 30 '16 00:07 machineghost

Hmm - what version of enzyme and React are you using?

ljharb avatar Jul 30 '16 00:07 ljharb

"enzyme": "^2.4.1",
"react": "^0.14.3",

machineghost avatar Jul 30 '16 00:07 machineghost

And how do you import "shallowRender"?

ljharb avatar Jul 30 '16 00:07 ljharb

Oh dear lord I'm a moron. There was a mistake in my import, and I was actually using a different shallowRender (a home-grown one from pre-Enzyme) without realizing it.

Thank you SO much, and sorry for the stupidity.

machineghost avatar Jul 30 '16 00:07 machineghost

Hi

I have tried below solution for calling methods of component and it is working fine for components having state.

But, I have one stateless component and I want to test one method of that component ans I am getting below error.

//Error ` TypeError: wrapper.instance(...).setFocusToTextBox is not a function

  at Object.<anonymous> (src\Engines\LeadershipTrait\__test__\RatingInput.test.js:69:28)

`

// Stateless component method ` const setFocusToTextBox = (index) => {

 window.setTimeout(function () {
        let textbox = document.getElementById("rating"+props.index+index);                    
        textbox.focus();
    },0);
}`

// Testcase ` /*Checking setToFocus method/ it('Checking setToFocus method', () => {

     let enteredRating = [[1,0,0,0,0,0]];        
    //render component for even number row with selectedRating
    let wrapper = shallow(<RatingInput index={oddIndex} ratingEntered={enteredRating} rating={rating}/>);
    wrapper.instance().setFocusToTextBox(1);        
});`

Please guide where i am doing mistake.

Thank you, Nikunj.

nikunjgami1991 avatar Dec 30 '16 11:12 nikunjgami1991

Stateless components can't possibly have any methods, because they're not instances. That's just a function closed inside the SFC, and it's impossible to invoke it from tests unless you extract it from the rendered jsx.

ljharb avatar Dec 30 '16 17:12 ljharb

Thanks for guidance.

nikunjgami1991 avatar Jan 02 '17 06:01 nikunjgami1991

I'm having trouble when I try to get the wrapper instance for a component which is written using class.

class MyComponent extends Component {
  myMethod() {
    // ...
  }
}

// on test files
const wrapper = shallow( <MyComponent /> ).instance();

wrapper.myMethod() // -> undefined

In short, the wrapper instance doesn't have the methods of the Component. Am I doing something wrong?

retrofox avatar Feb 07 '17 16:02 retrofox

@retrofox that seems to work - if it didn't have the method, it would throw a TypeError. Returning undefined might be what myMethod does?

ljharb avatar Feb 07 '17 16:02 ljharb

@retrofox that seems to work - if it didn't have the method, it would throw a TypeError. Returning undefined might be what myMethod does?

Nop. The method is not defined.

TypeError: wrapper.myMethod is not a function
      at Context.<anonymous> (index.jsx:81:8)

retrofox avatar Feb 07 '17 18:02 retrofox

@retrofox what does instance() return?

aweary avatar Feb 07 '17 18:02 aweary

sorry @aweary. I was wrapping the MyCompnent component with a translation helper. I don't know exactly what is the issue in our code but definitely I'll have to dive on this. Thanks for your comments and I'm sorry for disturbing.

retrofox avatar Feb 07 '17 18:02 retrofox

@ljharb I saw this in one of your comments above. const wrapper = shallow(

@smoholkar i'll have to see the implementation of Num to answer that.

ljharb avatar Feb 22 '17 06:02 ljharb

@ljharb It's huge but this is the skeleton of it : ``

class Num extends React.Component {

state = {
  value = this.props.path || ''
}

componentWillReceiveProps(newProps) {
    if (newProps.path !== undefined && this.props.path !== newProps.path) {
      this.setState({ value: newProps.path });
    }
}

getNumberDetails() {
// ......
// does some processing & then returns the value
returns value 
}

render() {
  const result = getNumberDetails() // I'm testing for correctness of the value of result. 
  
return (
   <Wrapper1 value = {result}>
        <Wrapper2 value = {result}> 
        </Wrapper2>
   <Wrapper1>
)

}


sonali-moholkar avatar Feb 22 '17 15:02 sonali-moholkar