How to mock RxJs BehaviorSubject or Observables for testing?

Viewed 359

I've created a sample react hook which I want to test. The hooks imports an subject from another file and subscribe to it. On completion of that subject the internal state of the hook changes.

sampleBehaviourSubject.ts

export const subject = new BehaviorSubject<string>("I'm just an example")

useSample.js

const useSample(){

 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.

0 Answers
Related