Creating a test from Angular query parameter returned as a promise

Viewed 1556

I have my TestBed configuration with the following provider:

{
provide: ActivatedRoute,
useValue: {
    queryParams: of({fooObservable: true})
  }
},

how can I write a jasmine spy that accesses this query parameter and tests whether it's true or false? I have done the following but I can't access it in order to test it. fooSpy = spyOn(this.ActivatedRoute.queryParams, 'queryParams');

1 Answers

This is tricky. Here is how I did it:

const spyParamMap = jasmine.createSpyObj({get: null});
const mockActivatedRoute = { paramMap: of(spyParamMap) };

Then in providers array: { provide: ActivatedRoute, useValue: mockActivatedRoute }

And finally in tests:

spyParamMap.get.and.returnValue('tFilename');
fixture.detectChanges();

In my ngOnInit() I have the following snippet:

this.route.paramMap.subscribe(params => {
    this.dlFilename = params.get('download');
    if (this.dlFilename) {
         // logic for if a filename is passed
    }

so I can pass in a result to params.get() and test my logic inside the if.

I hope this helps.

Related