Skip to content

Instantly share code, notes, and snippets.

@dvaJi
Created May 16, 2019 23:35
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dvaJi/cf552bbe6725535955f7a5eeb92d7d2e to your computer and use it in GitHub Desktop.
Save dvaJi/cf552bbe6725535955f7a5eeb92d7d2e to your computer and use it in GitHub Desktop.
Mock ActivatedRoute (with snapshot, queryParams and params), tested in Angular 7+
import { Params } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
export class MockActivatedRoute {
private innerTestParams?: any;
private subject?: BehaviorSubject<any> = new BehaviorSubject(this.testParams);
params = this.subject.asObservable();
queryParams = this.subject.asObservable();
constructor(params?: Params) {
if (params) {
this.testParams = params;
} else {
this.testParams = {};
}
}
get testParams() {
return this.innerTestParams;
}
set testParams(params: {}) {
this.innerTestParams = params;
this.subject.next(params);
}
get snapshot() {
return { params: this.testParams, queryParams: this.testParams };
}
}
// details were omitted
// Import the mock class
import { MockActivatedRoute } from './mock-active-router';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let activatedRouteStub: MockActivatedRoute;
beforeEach(async(() => {
activatedRouteStub = new MockActivatedRoute();
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [
{ provide: ActivatedRoute, useValue: activatedRouteStub }
]
}).compileComponents();
}));
it('should change params', () => {
expect(component.myparam).toBeUndefined();
expect(component.paramTwo).toBeUndefined();
activatedRouteStub.testParams = {
myparam: 'value',
paramTwo: 1
};
fixture.detectChanges();
expect(component.myparam).toEqual('value');
expect(component.paramTwo).toEqual(1);
});
@bilelz
Copy link

bilelz commented May 10, 2021

Thanks!

@StudioSpindle
Copy link

💯

@enmy726
Copy link

enmy726 commented Apr 14, 2022

Thank you! Helpful

@Andrei-Fogoros
Copy link

Hello,
Could you please provide us with the license for the above code?

Thank you!

@morjuax
Copy link

morjuax commented Nov 24, 2022

Thanks, super Helpful

@jimyhdolores
Copy link

Gracias!!

@SimonStorlSchulke
Copy link

You just ended my 3 hour descent into madness. Thank you <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment