如何解决Angular w / Jasmine和Karma测试了模拟服务
我想使用Jasmine / Karma来测试模拟服务,而无需了解真正的服务。问题是它希望我添加真实服务中的所有依赖项,例如HttpErrorHandler和MessageService。
这是下面的真实服务代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { httpOptions } from '../http-options';
import { HttpErrorHandler,HandleError } from '../http-error-handler.service';
//
@Injectable({ providedIn: 'root' })
export class AboutService {
private handleError: HandleError;
constructor(
private http: HttpClient,httpErrorHandler: HttpErrorHandler
) {
this.handleError = httpErrorHandler.createHandleError('AboutService');
}
// Skills
////////
getSkills() {
const url = 'path';
return this.http.get<any>(url,httpOptions)
.pipe(
catchError(this.handleError('getSkills',[]))
);
}
}
和我的.spec文件
import { async,ComponentFixture,TestBed } from '@angular/core/testing';
import { AboutComponent } from './about.component';
//
import { HttpClientTestingModule,HttpTestingController } from '@angular/common/http/testing';// Other imports
import { AboutService } from './about.service';
// import { HttpErrorHandler } from '../http-error-handler.service';
// import { MessageService } from '../message.service';
// import { MaterialModule } from "../material/material.module";
class MocksService extends AboutService{
// getSkills() {
// return [someRandomArray];
// }
}
describe('AboutComponent',() => {
let component: AboutComponent;
let fixture: ComponentFixture<AboutComponent>;
//
let httpTestingController: HttpTestingController;
let service: AboutService;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ AboutComponent ],imports: [ HttpClientTestingModule,MaterialModule ],providers: [
{ AboutService,useClass: MocksService },// HttpErrorHandler,// MessageService
]
})
.compileComponents();
//
httpTestingController = TestBed.get(HttpTestingController);
service = TestBed.get(AboutService);
}));
beforeEach(() => {
fixture = TestBed.createComponent(AboutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create',() => {
expect(component).toBeTruthy();
});
it('should be created',() => {
const service: AboutService = TestBed.get(AboutService);
expect(service).toBeTruthy();
});
});
解决方法
您可以注入它并创建间谍来模拟您要模拟/测试的内容:
const aboutService = TestBed.inject(AboutService);
const spy = spyOn(aboutService,'getSkills').and.returnValue(of({...});
...
expect(spy).toHaveBeenCalled();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。