错误:没有Http提供商!组件的业力测试

时间:2017-11-06 12:04:38

标签: angular karma-jasmine

我有什么:服务提供商依赖于Http,需要进行测试

MyService.ts:

@Injectable()
export class MyService {
 constructor(private http: Http) {
 }

 someFunction() {
   return this.http.get(URL)
   .map((res: Response) => {
    res.json();
   });
 }
} 

MyComponent.ts:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})

export class MyComponent implements OnInit {
  constructor(private myService: MyService) {}
}

当我运行ng测试时,错误

myComponent没有http提供程序出现 ,应创建MyService

MyComponent.spec.ts:

 describe('MyComponent', () => {
   let component: MyComponent;
   let fixture: ComponentFixture<MyComponent>;

   beforeEach(async(() => {
     TestBed.configureTestingModule({
       imports: [
         HttpModule
       ],
       declarations: [ MyComponent],
       providers: [
         MockBackend,
         BaseRequestOptions,
         {
           provide: HttpClient,
           useFactory: (backendInstance: MockBackend, defaultOptions:           BaseRequestOptions) => {
             return new Http(backendInstance, defaultOptions);
           },
           deps: [MockBackend, BaseRequestOptions]
         },
         MyService
       ]
     })
     .compileComponents();

   }));

   beforeEach(() => {
     fixture = TestBed.createComponent(MyComponent);
     component = fixture.componentInstance;
     // fixture.detectChanges();
   });

   it('should be created', () => {
     expect(component).toBeTruthy();
   });
 });

我尝试了什么 我试过的就是那里!我还阅读了有关MockBackend的内容,并在this link显示的服务中对其进行了补充!但它对我没有用!

任何帮助?

1 个答案:

答案 0 :(得分:1)

实际上我在service.spec.ts文件中缺少导入 HTTP模块提供HTTP,ConnectionBackend ,而不仅仅是在component.spec.ts文件中。