我试图在我的blogs.component.spec.ts文件中为我的BlogService类(它使用Firestore)创建一个服务存根,因为我想测试我的组件,但我总是得到以下错误:
R3InjectorError(DynamicTestModule)[BlogService -> BlogService]:
NullInjectorError: No provider for BlogService!
NullInjectorError: R3InjectorError(DynamicTestModule)[BlogService -> BlogService]:
NullInjectorError: No provider for BlogService!
问题是我提供了服务,这是我的blog。component。spec。ts文件:
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { BlogsComponent } from './blogs.component';
import { BlogService } from '../../services/blog.service';
import { of } from 'rxjs';
import { RouterTestingModule } from '@angular/router/testing';
describe('BlogsComponent', () => {
let component: BlogsComponent;
let fixture: ComponentFixture<BlogsComponent>;
const serviceStub = {
getBlogById: (id: string) =>
of({ id: id, title: '', description: '', imagePath: '' }),
};
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [BlogsComponent],
imports: [RouterTestingModule],
providers: [{ provider: BlogService, useValue: serviceStub }],
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(BlogsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});
这是我的blogs.component.ts文件:
import { Component, OnInit } from '@angular/core';
import { BlogService } from '../../services/blog.service';
import { Blog } from '../../models/blog';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'blogsite-blogs',
templateUrl: './blogs.component.html',
styleUrls: ['./blogs.component.css'],
})
export class BlogsComponent implements OnInit {
blog: Blog | undefined;
blogId: string | null | undefined;
constructor(
private route: ActivatedRoute,
private blogService: BlogService
) {}
ngOnInit(): void {
this.blogId = this.route.snapshot.paramMap.get('id');
if (this.blogId) {
this.blogService.getBlogById(this.blogId).subscribe((blog) => {
this.blog = blog;
});
}
}
}
这是我的服务类:
import { Injectable } from '@angular/core';
import {
AngularFirestore,
AngularFirestoreCollection,
} from '@angular/fire/firestore';
import { Blog } from '../models/blog';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable()
export class BlogService {
blogCollection: AngularFirestoreCollection<Blog>;
private blogIdSource = new BehaviorSubject('');
currentId: Observable<string> = this.blogIdSource.asObservable();
constructor(public db: AngularFirestore) {
this.blogCollection = this.db.collection<Blog>('Blog');
}
getBlogs(): Observable<Blog[]> {
return this.blogCollection.valueChanges({idField: 'id'});
}
getBlogById(id: string): Observable<Blog | undefined> {
return this.blogCollection
.doc(id)
.valueChanges();
}
}
我还试图在另一个组件中测试它,它实际上在那里工作,我只是为我的serviceStub使用了另一个方法。有人知道为什么它不能在我的博客组件工作吗?
Tryprovide
notprovider
providers: [{ provide: BlogService, useValue: serviceStub }],