I am trying to test an Angular Component using the ActivatedRoute Class in Karma/Jasmine but I'm having a very annoying error that I can't fix. Error: Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?)
I have tried all solutions I found online, mocking an Activated Route in various ways. But I just can't get it to work.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { SearchbarComponent } from './searchbar.component';
describe('SearchbarComponent', () => {
let component: SearchbarComponent;
let fixture: ComponentFixture<SearchbarComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ SearchbarComponent ],
providers: [
{
provide: ActivatedRoute,
useValue: {
queryParams: of(convertToParamMap({
search: ""
}))
}
}
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Input, Component, HostListener, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
...
@Component({
selector: 'searchbar',
templateUrl: './searchbar.component.html',
styleUrls: ['./searchbar.component.scss'],
providers: [ ActivatedRoute ]
})
export class SearchbarComponent implements OnInit {
constructor(private route: ActivatedRoute) {
this.route.queryParams
.subscribe(params => {
this.currentSearch = params.search;
});
}
...
}
RouterTestingModule
handles the mocks of all the routing-related things, including ActivatedRoute. You can delete the providers
section and I would expect it to work
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute, convertToParamMap } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { SearchbarComponent } from './searchbar.component';
describe('SearchbarComponent', () => {
let component: SearchbarComponent;
let fixture: ComponentFixture<SearchbarComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ SearchbarComponent ],
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(SearchbarComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With