angular - Angular 单元测试 TypeError:this.http.get(...).pipe 不是函数
问题描述
我正在按照这个示例对服务进行单元测试(获取来自 Spring 应用后端的请求)https://angular.io/guide/testing#testing-http-services
服务等级:
@Injectable()
export class TarifService {
constructor(private messageService: MessageService, private http: HttpClient) { }
public getTarifs(): Observable<Tarif[]> {
return this.http.get<Tarif[]>(tarifffsURL).pipe(
tap(() => {}),
catchError(this.handleError('getTarifs', []))
);
}
}
单元测试
describe('TarifService', () => {
let tarifService: TarifService;
let httpClientSpy: { get: jasmine.Spy };
let expectedTarifs;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ToastrModule.forRoot(), HttpClientModule, HttpClientTestingModule],
providers: [TarifService, HttpClient, MessageService]
});
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
tarifService = new TarifService(<any> MessageService,<any> httpClientSpy);
});
it('should be created', inject([TarifService], (service: TarifService) => {
expect(service).toBeTruthy();
}));
it('should return expected tarif (HttpClient called once)', () => {
const expectedTarifs: Tarif[] =
[{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
httpClientSpy.get.and.returnValue(expectedTarifs);
tarifService.getTarifs().subscribe(
tarifs => expect(tarifs).toEqual(expectedTarifs, 'expected tarifs'),
fail
);
expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
});
});
运行测试时,我一直有这个错误
TarifService should return expected tarif (HttpClient called once)
TypeError: this.http.get(...).pipe is not a function
这可能是什么原因?
解决方案
问题是,当你spy
被调用时,它返回一个Array
,并且Array
没有pipe
函数。Observable
你需要从你的返回一个spy
,像这样
const expectedTarifs: Tarif[] =
[{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
httpClientSpy.get.and.returnValue(Observable.of(expectedTarifs));
看看returnValue
情况如何Observable.of(expectedTarifs)
。Observable.of
创建一个Observable
发出你指定为参数的一些值,一个接一个,然后发出一个完整的通知。查看文档
在最新版本中rxjs
我们可以使用of
操作符
import { of } from 'rxjs';
//... omitting some code here for brevity
const expectedTarifs: Tarif[] =
[{ id: 1, name: 'Tarif1', value: '20' }, { id: 2, name: 'Tarif2', value:'30' }];
httpClientSpy.get.and.returnValue(of(expectedTarifs));
希望能帮助到你
推荐阅读
- selenium - 在 Windows 窗体中嵌入 Selenium ChromeDriver
- git - 即使我在本地添加了文件夹,git 也会看到所有内容都是最新的
- json - Dart json.encode 没有按照 Firebase 函数的需要进行编码
- r - 无法在 R 中安装 keras
- python - 运行 Django 教程时出错:找不到页面
- c++ - 命名空间 std 中是否有分配给变量的函子?
- c++ - 无法在 Windows 上使用 CMake 链接 Lua 5.3.4:找不到 Lua(缺少:LUA_LIBRARIES)(找到版本“5.3.4”)
- go - 确保仅检索一次值
- php - 使用PHP删除网络驱动器上隐藏文件夹中的文件?
- android - android - 包重命名后的新应用程序版本