Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.refs is undefined for shallow tests using enzyme on React native

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.

like image 827
Bajju Avatar asked Sep 29 '17 01:09

Bajju


1 Answers

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
    }))
  }
}
like image 130
Bajju Avatar answered Oct 11 '22 13:10

Bajju