Testing component methods
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 const wrapper = shallow(<Button />); wrapper.instance().handleClick()
That is so nice, thanks for the fast response @ljharb!
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 that's the console inspection which shows enumerable properties. Try actually checking .instance on it.
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.
Hmm - what version of enzyme and React are you using?
"enzyme": "^2.4.1",
"react": "^0.14.3",
And how do you import "shallowRender"?
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.
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.
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.
Thanks for guidance.
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 that seems to work - if it didn't have the method, it would throw a TypeError. Returning undefined might be what myMethod does?
@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 what does instance() return?
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.
@ljharb I saw this in one of your comments above. const wrapper = shallow(); wrapper.instance().handleClick()
I am working on a similar issue: How do I get the correct value of a method() if the method returns a different value on componentWillReceiveProps?
I tried to do the following
const component = shallow(<Num {...properties} />);
component.instance().getNumberDetails() --> should return 1000.00 which it does
component.update()
component.instance().getNumberDetails() --> should return $1,000.00 but it doesn't seem to be updated.
(I might have to setState explicitly here before component.update()? But I am testing for the value itself. What's the right way to test this? )
@smoholkar i'll have to see the implementation of Num to answer that.
@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>
)
}