I have a component, service and mock service. I am writing a simple test for the component but I get an error while testing. I want to use the MyMockService instead of MyService via useClass.
Angular Version: 11.0.6 Node Version: 14.15.4
component:
export class MyComponent implements OnInit, OnDestroy {
constructor(
private sharedService: MySharedService,
private myService: MyService) {}
...
}
spec.file:
import { CommonModule } from '@angular/common';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { MyService } from '../my.service';
import { MySharedService } from '../my-shared.service';
import { MyMockService } from '../my.service.mock';
import { CountriesComponent } from './countries.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
let service: MyService;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
CommonModule,
ReactiveFormsModule,
],
providers: [
{ provide: MyService, useClass: MyMockService }, // <--
MySharedService,
],
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent); // <-- ERROR !!!
service = TestBed.inject(MyService);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
my.service:
@Injectable()
export class MyService extends MyBaseService {
baseUrl = '/baseUrl/...';
constructor(
protected hc: HttpClient
) {
super(hc);
}
get() {
return this.hc.get<any[]>(`${this.baseUrl}`);
}
}
my.service.mock:
@Injectable()
export class MyMockService {
arr: any[] = [];
constructor(
) { }
get() {
return of(JSON.parse(JSON.stringify(this.arr)));
}
}
I get an error when the component is created:
NullInjectorError: R3InjectorError(DynamicTestModule)[MyService -> MyService]:
NullInjectorError: No provider for MyService !
How can i fix this?
The problem was in the file path. I had another service with the same name. I changed the path from
import { MyService } from '../my.service';
to
import { MyService } from '../right path/my.service';