facebookarchive / draft-js

A React framework for building text editors.
https://draftjs.org/
MIT License
22.57k stars 2.64k forks source link

Focusing editor using useEffect hook crashes tests #2426

Open nickbreid opened 4 years ago

nickbreid commented 4 years ago

Do you want to request a feature or report a bug? Bug

What is the current behavior? Jest test crashes on valid setup

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. You can use this jsfiddle to get started: https://jsfiddle.net/gmertk/e61z7nfa/. Here's a codesandbox: https://codesandbox.io/s/blissful-hermann-w08f2?file=/test/MyEditor.test.js

The issue appears when a component instantiates an Editor and uses the useEffect hook to automatically focus the editor when it's mounted. This functions correctly outside the test atmosphere. But using jest and @testing-library/react, when the component is instantiated, the function setDraftEditorSelection throws the following error:

documentObject.defaultView.getSelection is not a function

What is the expected behavior?

The expected behavior is that this component could be instantiated successfully by the test runner.

Which versions of Draft.js, and which browser / OS are affected by this issue? Did this work in previous versions of Draft.js? Draft: 0.11.5 jest: 26.0.1 @testing-library/react 10.0.4

zachdixon commented 4 years ago

@nickbreid I'm running into this error and just wondering if you've had any luck fixing it or workarounds? I'm not using a hook to autofocus like you are and still getting the error, so thinking it maybe something else?

nickbreid commented 4 years ago

@zachdixon I implemented a hacky workaround which I'm not proud of.

In my test environment, I created a global variable isJest and set it to true. Then in my useEffect hook I added a condition essentially enforcing, if (global.isJest) return; to avoid executing the code which provokes the Draft bug.

To be clear, this is actually changing my component's behavior to create a trap door for the test to fall into. I'm surprised I even managed to get an approval on that PR... 😄

zachdixon commented 4 years ago

@nickbreid lol gotcha. I guess I'll have to dig some more to see which part of my code is actually causing the error. Thanks for the quick response!