Do you want to request a _feature_ or report a _bug_?
Report a bug
What is the current behavior?
Ref methods cause an error to be thrown
If the current behavior is a bug, please provide the steps to reproduce and
either a repl.it demo through https://repl.it/languages/jest or a minimal
repository on GitHub that we can yarn install and yarn test.
import React from 'react'
import renderer from 'react-test-renderer'
it('Test refs', () => {
class Comp extends React.Component {
componentDidMount () {
console.log(this.myRef)
this.myRef.addEventListener('click', () => console.log('click'))
}
render () {
return (
<div ref={div => { this.myRef = div }}>foo</div>
)
}
}
const tree = renderer.create(
<Comp />
).toJSON()
expect(tree).toMatchSnapshot()
})
Cannot read property 'addEventListener' of null
What is the expected behavior?
For refs to work and have usable mock methods. I did some digging through other issues and it looks like this was fixed here https://github.com/facebook/react/issues/7740 but I'm not sure if ref DOM methods were ever fixed.
Please provide your exact Jest configuration and mention your Jest, node,
yarn/npm version and operating system.
MacOS
react-test-renderer @ 16.2.0
jest @ 21.2.1
react @ 16.1.1
node @ 8.2.1
yarn @ 0.27.5
Do you have a repro of that? Does Cannot read property 'addEventListener' of null comes from Jest or react-test-renderer? I'd assume the latter, but who knows without a repo and full error message 🤷♂️
@thymikee Here is a repo https://github.com/mildrenben/jest-ref-issue
I believe it's being thrown by react-test-renderer
You've linked to the correct issue in react's tracker - react-test-renderer does not support ref. You can either use ReactDOM or enzyme to do a real render.
Also see React docs about createNodeMock: https://reactjs.org/docs/test-renderer.html#ideas for an alternative.
Either way, this is not a jest issue
createNodeMock seems perfect, thanks!
Most helpful comment
Also see React docs about
createNodeMock: https://reactjs.org/docs/test-renderer.html#ideas for an alternative.Either way, this is not a jest issue