You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I've created a sample React hook which I want to test. The hooks imports an subject from another file and subscribes to it. On completion of that subject the internal state of the hook changes.
sampleBehaviourSubject.ts
exportconstsubject=newBehaviorSubject<string>("I'm just an example")
useSample.js
constuseSample(){const[state,setState]=useState("Nothing to show here")useEffect(()=>{subject.subscribe({complete: ()=>setState("The subject is completed")})},[])return[state]}
I'm new to unit testing but I know that external dependencies can be mocked/stubbed using sinon.js . But I'm not able to figure out how can I mock an Observable/Subject and test this useSample hook. It'll be great if someone shows an example with @testing-library/react-hooks
Please note that this subject is subscribed at many other places hence I want to restore the mock/stub afterEach spec runs.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
The question is also posted on Stackoverflow
https://stackoverflow.com/questions/70343832/how-to-mock-rxjs-behaviorsubject-or-observables-for-testing
I've created a sample React hook which I want to test. The hooks imports an subject from another file and subscribes to it. On completion of that subject the internal state of the hook changes.
sampleBehaviourSubject.ts
useSample.js
I'm new to unit testing but I know that external dependencies can be mocked/stubbed using sinon.js . But I'm not able to figure out how can I mock an Observable/Subject and test this
useSample
hook. It'll be great if someone shows an example with@testing-library/react-hooks
Please note that this subject is subscribed at many other places hence I want to restore the mock/stub afterEach spec runs.
Beta Was this translation helpful? Give feedback.
All reactions