当我尝试测试时,显示错误...。
NullInjectorError: R3InjectorError(DynamicTestModule)[AlertService -> InjectionToken config -> InjectionToken config]:
NullInjectorError: No provider for InjectionToken config!
这是我的组件...
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ApiService } from '../services/api.service';
import { AlertService } from 'ngx-alerts';
import { NgxSpinnerService } from "ngx-spinner";
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-deliveryaddress',
templateUrl: './deliveryaddress.component.html',
styleUrls: ['./deliveryaddress.component.scss']
})
export class DeliveryaddressComponent implements OnInit {
billingAddress: FormGroup;
deliveryAreas: any;
constructor(
public router: Router,
private formBuilder: FormBuilder,
public apiService: ApiService,
private alertService: AlertService,
private spinner: NgxSpinnerService,
private modalService: NgbModal) {
this.spinner.show();
this.billingAddress = this.formBuilder.group({
'streetAddress': ['', Validators.compose([Validators.required])],
'instructions': [null]
});
localStorage.setItem('val', '0');
if(localStorage.getItem('recipientDetails')){
this.router.navigate(['product']);
}
}
ngOnInit() {
this.apiService.getDeliveryAreas().subscribe((res)=>{
this.deliveryAreas = res.body.deliveryAreas;
this.spinner.hide();
});
}
get streetAddress() {
return this.billingAddress.get('streetAddress');
}
address:any;
this.address = {
streetAddress : this.billingAddress.value.streetAddress,
}
this.apiService.getVendors(this.address.zipCode).subscribe((res)=>{
if(res && res.body && res.body.error){
this.alertService.danger(res.body.error);
this.spinner.hide();
}
});
}
}
............................................... ................................................... ................................................... ................................................... ................................................... ................................................... ................................................... ................................................... .....................
答案 0 :(得分:1)
构造函数中有一个alertService,为进行测试,您将必须提供以下服务:
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
{ provide: AlertService, useClass: TestAlertService }
]
}).compileComponents();
}));
此TestAlertService应该为所有需要的请求提供模拟数据。
-评论后编辑:-
您的TestAlertService作为函数应具有危险性,因为它在原始代码中用作函数。最终的返回值必须是正确的类型(布尔值,字符串等)
class TestAlertService {
danger(value:string) {
}
}
如果这还不够,请添加一段您的TestAlertService代码,以便我提供更具体的帮助