Created
May 16, 2019 23:35
Mock ActivatedRoute (with snapshot, queryParams and params), tested in Angular 7+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You just ended my 3 hour descent into madness. Thank you <3