由于某种原因,我无法使模拟数据工作。这样就可以创建组件了
NullInjectorError:R3InjectorError(DynamicTestModule)[ListingsService - > AuthService - > MessageService - > MessageService]:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ListingsComponent } from './listings.component';
import { dummyListings } from 'src/app/dummy data/dummyListings';
import { dummyUsers } from 'src/app/dummy data/dummyUsers';
import { ListingsService } from 'src/app/services/listings.service';
import { JwtHelperService } from '@auth0/angular-jwt';
class MockJwtHelperService {
}
describe('listings Component', () => {
let component: ListingsComponent;
let fixture: ComponentFixture<ListingsComponent>;
let jwtHelper: JwtHelperService;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ListingsComponent],
imports: [HttpClientTestingModule],
providers: [
ListingsService,
{ provide: JwtHelperService, useClass: MockJwtHelperService }
]
}).compileComponents();
fixture = TestBed.createComponent(ListingsComponent);
jwtHelper = TestBed.get(MockJwtHelperService);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the Component', () => {
expect(component).toBeTruthy();
});
});
我希望创建我的组件,但我不断收到此错误。
只需用空类模拟
MessageService
并在进一步添加测试用例时添加方法:
...
class MockMessageService {
}
...
...
TestBed.configureTestingModule({
declarations: [ListingsComponent],
imports: [HttpClientTestingModule],
providers: [
ListingsService,
{ provide: JwtHelperService, useClass: MockMessageService },
{ provide: JwtHelperService, useClass: MockJwtHelperService }
]
}).compileComponents();
...
上述方法也可以对
AuthService
甚至ListingsService
进行。
另一种方法是将 MessageService 添加到提供者数组中,因为任何模块中都没有提供它:
...
TestBed.configureTestingModule({
declarations: [ListingsComponent],
imports: [HttpClientTestingModule],
providers: [
MessageService,
ListingsService,
{ provide: JwtHelperService, useClass: MockMessageService },
{ provide: JwtHelperService, useClass: MockJwtHelperService }
]
}).compileComponents();
...
最后,我们可以使用
providedIn: 'root'
在根级别提供 MessageService,这将确保服务可用,而无需在测试文件中导入任何内容,但它可能会影响您的应用程序,所以请尝试将此作为最后的手段。