I have a component which has 2 input text fields.
In the componentDidMount()
method I am calling this.refs.password.focus();
There is some amount of tricky business logic sitting inside my componentDidMount
but while doing a shallow unit test on componentDidMount
, I get error
cannot access password of undefined
I checked the instance of the shallow component and see that this.refs
is undefined.
My question is how can we set this through tests?
Shallow has a second parameter which we can pass called as the context where we can set the context for unit testing but it seems to be doing nothing.
Any help around this area would be highly appreciated.
The easiest approach for this problem would be to set the refs
through the instance.
const component = shallow(<Component />)
const instance = component.instance()
instance.refs = {
password: {
getRenderedComponent: jest.fn(() => ({
focus: jest.fn
}))
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With