gpt4 book ai didi

Angular 6 - NullInjectorError : No provider for HttpClient in unit tests

转载 作者:太空狗 更新时间:2023-10-29 17:23:00 36 4
gpt4 key购买 nike

我正在如下服务中导入和使用 HttpClient:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
providedIn: 'root',
})
export class MyService {
constructor(private http: HttpClient) { }

getData() {
return this.http.get("url...");
}
}

但是,当我为我的单元测试 运行ng test 时,当这些测试使用该服务时,我收到错误:

Error: StaticInjectorError(DynamicTestModule)[HttpClient]: 
StaticInjectorError(Platform: core)[HttpClient]:
NullInjectorError: No provider for HttpClient!

Angular 6 documentation on HTTP只是说要做我上面做的事。

最佳答案

import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
import { myService } from './myservice';


describe('myService', () => {

beforeEach(() => TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [myService]
}));

it('should be created', () => {
const service: myService = TestBed.get(myService);
expect(service).toBeTruthy();
});

it('should have getData function', () => {
const service: myService = TestBed.get(myService);
expect(service.getData).toBeTruthy();
});

});

关于 Angular 6 - NullInjectorError : No provider for HttpClient in unit tests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53769401/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com