我创建了虚假服务:
@Injectable()
class MockClientService {
CHAT_URL = '';
public planOrders = new Subject<PlanOrderModel[]>();
private subject: Rx.Subject<MessageEvent>;
constructor() {
this.planOrders.next([{
PlanDirective: 'Create Directive', Physician: 'REMOTE-RO', PlanPriority: 2,
PlanNotes: '', PlanOrderId: 'Order_1', PatientDetails: { 'ID': '210598', 'Name': 'Ruffin Abdullah', 'AnonymizedID': '' },
StructureSetID: 'CT_1', MachineID: 'Scanner Test', LastUpdated: '05/12/2018', DueDate: '05/12/2018', Status: '2',
GatewayID: 0, selected: false, active: true
}]);
} }
这是我的TestBed:
TestBed.configureTestingModule({
imports: [FormsModule, TableModule, DialogModule, HttpClientModule, RouterTestingModule.withRoutes([
{ path: 'Orders', component: PlanOrderComponent },
{ path: 'plan-order-history', component: PlanOrderHistoryComponent }
])],
declarations: [HeaderComponent, SubheaderComponent, PlanOrderComponent, FilterPlanOrderPipe,
PlanOrderHistoryComponent],
providers: [PlanOrderService, ToastsManager, ToastOptions,
ConfirmationService, ViewContainerRef, DataServiceService, AppService]
}).overrideComponent(PlanOrderComponent, {
set: {
providers: [
{ provide: ClientService, useClass: MockClientService }
]
}
});
即使在注入MockClientService并得到错误之后: NullInjectorError:没有MockClientService提供程序
答案 0 :(得分:1)
正如评论中已经提到的那样,不需要调用overrideComponent
,您可以像这样在providers
数组中提供模拟服务:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ DummyComponent ],
providers: [{
provide: ClientService,
useClass: MockClientService
}]
}).compileComponents();
}));
我进行了一次小型的堆叠闪电战,展示了如何在单元中模拟服务 测试 here。