I have triggered a change in component using react testing library and I want to check the corresponding change in the state of the component. Is it possible to check the state of the component
Probably a No-Go as this is a direct violation of the principles of React-Testing-Library
The problem
You want to write maintainable tests for your React components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.
This solution
The more your tests resemble the way your software is used, the more confidence they can give you.
Basically, it doesn't concern itself with the internal implementation details of a component, like state
, but rather its API, i.e. the props and how a user can interact with it. It's more like black-box testing.
Disclaimer: I agree that using inner state of component for testing isn't nice practice. But there are sometimes situations where you are forced to, otherwise use case would not be tested at all.
Example: You want to change position of cursor in draft-js. That is impossible via browser/JSDOM events. You need to use dradt-js API for that. draft-js EditorState is stored as react state within the component. So in order to test this test case you are forced to manipulate inner state of the component.
Option is to use Enzyme APIs state and setState. Yes that means using Enzyme (for such exceptional cases) and react-testing-library in one project
But in my test I was facing also Enzyme issue, which is not worth mentioning, so I ended up doing such nasty trick. In production component itself, I stored state and setter into global variables. I named them so that it is obviously not good idea to use them in production:
export let innerStateFOR_TESTING; export let setInnerStateFOR_TESTING; const Component = () => { const [innerState, setInnerState] = React.useState(null); innerStateFOR_TESTING = innerState; setInnerStateFOR_TESTING = setInnerState; ... }
In test I can than render the component, which would fill in those global variables. Than I can manipulate/check inner state for testing purposes.
I wish there would be option in react-testing-library. It can be discouraged practice, but if your other option is not test certain scenario, it would be available.
© 2022 - 2024 — McMap. All rights reserved.