Component:
@Component({
selector: 'app-test',
templateUrl: './test.component.html'
})
export class TestComponent implements OnInit {
useCase: string;
constructor(
private route: ActivatedRoute,
) {}
ngOnInit() {
this.route.queryParams.subscribe(param => {
if (param) {
this.useCase = param.u;
}
});
}
}
Test Spec
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
AppModule
],
providers: [
{ provide: ActivatedRoute, useValue: ??? }
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
expect(component.useCase).toBeFalsy();
});
it('should set useCase variable with query string value', () => {
fixture.detectChanges();
// Set different route.queryParams here...
expect(component.useCase).toBe('success');
});
});
Using Angular 6, Karma and Jasmine for unit testing.
I am aware that we can set ActivatedRoute
to an object that will be used throughout the testing process by using:
providers: [
{ provide: ActivatedRoute, useValue: {
queryParams: Observable.of({id: 123})
} }
]
However, this approach sets the values for all test cases. Is there a way to dynamically change the ActivatedRoute
in each different test case?