Unit test queryParams subscription (Angular5)

I can't say if it is too late to answer this or not, but maybe it will help new googlers...

I manage to solve that this way:

class ActivatedRouteMock {
  queryParams = new Observable(observer => {
    const urlParams = {
      param1: 'some',
      param2: 'params'
    }
    observer.next(urlParams);
    observer.complete();
  });
}

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [
      HttpClientTestingModule
    ],
    providers: [
      HttpClient,
      HttpHandler,
      ControlContainer,
      {
        provide: ActivatedRoute,
        useClass: ActivatedRouteMock
      }
    ]
  }).compileComponents();

  injector = getTestBed();
  httpMock = injector.get(HttpTestingController);
}));

That allows you to assert the logic inside your .subscribe(() => {}) method..

Hope it hepls


You can use rxjs observable in useValue to mock it.

const router = {
  navigate: jasmine.createSpy('navigate')
};
beforeEach(async(() => {    
TestBed.configureTestingModule({
  imports: [
    RouterTestingModule.withRoutes([]),
    RouterTestingModule,
    PlanPrimengModule
  ],
  declarations: [YourComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  providers: [
    provideMockStore(),
    {
      provide: ActivatedRoute,
      useValue: {
        queryParams: of({
          param1: "value1",
          param1: "value2"
        })
      }
    },
    { provide: Router, useValue: router }
  ]
}).compileComponents();   }));