mocking a method in the same class during unittesting

10 views
Skip to first unread message

Kiflemariam Andom

unread,
Jun 23, 2019, 4:21:19 AM6/23/19
to Angular and AngularJS discussion
I have this class service in Angular 6:


   export class AppService {

     setValues(): Observable<any> {

       const vm: any = this;
       return new Observable(observer => {
       vm.currentValues().subscribe(data => {
           // continue modifying data and reset it

        });
     });
   }

   public currentValues(): Observable<any> {


   return new Observable(observer => {
     observer.next('data goes here')

    });

  } 
 }





The currentValues() returns certain values that setValues() modifies using some formula. How can unittest setValues() by mocking currentValues() to return fixed values so that I can compare the output consistently? I have wanted to do the following but not sure how to plug it in:



export function mockCurrentValues () : Observable<any> { return of( 'data' ) }



Sander Elias

unread,
Jun 25, 2019, 4:11:00 AM6/25/19
to Angular and AngularJS discussion
Hi Kiflemariam,

You can't really mock a method in the same class. Also, building your own subjects is not going to pan out in maintenance fees, returning new observables all over the place is going to end in major memory leakage.

export class AppService {
private currentValuesDB = new Subject<any>();
currentValues$ = this.currentValuesDB.asObservable();

setValues(): Observable<any> {
/**
* ok, as you are not providing a value. I assume there is
* something here that knows how to get that.
*/
this.currentValuesDB.next(/** whatever yo want to be in the subject. */)
return this.currentValues$.pipe(
map(oldValues => {
/** you might want to add some transformation here */
})
);
}
}

in this version, there is nothing to mock. you can grab the subject, and feed in whatever you need for testing. (even if it's a private!)
Reply all
Reply to author
Forward
0 new messages