lundi 7 septembre 2020

Testing with 2 different mocks in Jasmine

I have a ts guard like so:

@Injectable({
  providedIn: 'root'
})

export class AppEssentialsGuard implements CanActivate {

  private readonly DEFAULT_APP_ID = 'def';

  constructor(private appsService: AppsService) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const url = this.getDefaultAppUrl();
    if (url) {
      window.open(url);
    }
    return false;
  }

  private getDefaultAppUrl(): string {
    const myApp = this.appsService.getAllApps()
      .find(app => app.appId === this.DEFAULT_APP_ID);
    return myApp ? myApp.url : null;
  }
}

I am writing tests for it as follows:

describe('AppEssentialsGuard', () => {
  let guard: AppEssentialsGuard;
  let appsService: AppsService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        mockProvider(RequesterService),
        {provide: AppsService, useClass: AppsServiceMock}
      ]
    });
    appsService = TestBed.inject(AppsService);
    guard = TestBed.inject(AppEssentialsGuard);
  });

  it('should be created', () => {
    expect(guard).toBeTruthy();
  });

  it( 'should open new default app window', () => {
    spyOn(window, 'open');
    let returnValue = guard.canActivate(null, null);
    expect( window.open ).toHaveBeenCalledWith("https://appstore.com/");
    expect(returnValue).toBeFalsy();
  });


});

Now for the happy flow test, I am using the AppsServiceMock specified in useClass, which returns an array of dummy apps, including one with the ID 'def' for the test to pass.

My question is, I also want to test the case that this url returns an empty array, or one without the 'def' app, how can I test both cases? I don't know how to use another mock

I am new to Jasmine

Thanks!

Aucun commentaire:

Enregistrer un commentaire