0

I'm attempting to test a pretty complex service within my Angular application. To do this I need to be able to mock the number of different dependencies that the service has, I'm using spies to achieve this.

The service does a couple of different things with two of the dependencies within its constructor, and before I start testing the service I need to make sure it constructs properly, so I need to satisfy the requirements of the constructor.

The constructor has two separate subscriptions, one on a method that returns Observable<string> and one on a BehaviourSubject<boolean>.

constructor(
    private _translate: TranslateService,
    private _policiesService: PoliciesService,
  ) {
    _translate.get('services.filter').subscribe((filterObject: any) => {
      // do stuff...
    });

    this._policiesService.isPolicyLocked.subscribe(activePolicyLockState => {
      // do stuff...
    });
  }

I can easily mock the first subscription, by using a spy and then assigning a method and a return value in my beforeEach(), as below.

beforeEach(() => {
        spy_TranslateService = jasmine.createSpyObj('TranslateService', ['get', 'setDefaultLang']);
        spy_TranslateService.get.and.returnValue(of(translationFilterObject));

        //etc.. 
    });

But I can't do this with my behaviour subject, as it's not a method its a property of the PoliciesService. Is there a way that I can mock a property and give it a specific return value, similar to how I can with methods? Preferably without having to use getters and setters.

Jake12342134
  • 1,539
  • 1
  • 18
  • 45
  • Did you check out `spyOnProperty` of Jasmine? I did not use it yet, but maybe it helps in your case. Here is a conversation that may help: https://stackoverflow.com/questions/20879990/how-to-spyon-a-value-property-rather-than-a-method-with-jasmine – Milan Tenk Apr 15 '20 at 18:50

1 Answers1

0

Try:

spy_PoliciesService = jasmine.createSpyObj('PoliciesService', []);
spy_PoliciesService.isPolicyLocked = new BehaviorSubject(...); // mock what it should return in the ...
AliF50
  • 16,947
  • 1
  • 21
  • 37