[英]How to mock with strict TypeScript
例如:
let mockhttp; // 1
beforeEach(() => {
mockhttp = { //3
get: jest.fn()
};
mockhttp.get.mockReturnValue(of(...)); //4
});
it('should fetch', async () => {
const service = new MyService(mockhttp as any as HttpClient); //2
});
这将在 1 和 2 上给出以下错误。
Variable 'mockhttp' implicitly has type 'any' in some locations where its type cannot be determined.
改变let mockhttp;
let mockhttp: HttpClient;
给予 3:
Type '{ get: Mock ; }' is missing the following properties from type 'HttpClient': handler, request, delete, head, and 5 more.
并在 4:
TS2339: Property 'mockReturnValue' does not exist on type '{ (url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCred...'
有没有办法在不到处添加//@ts-ignore
情况下解决这个问题?
注意:这个问题与测试 httpclient 或任何相关内容无关。 它仅用于演示目的。 它可以是任何其他服务或组件。
Angular 提供了一个很好的包来测试 HTTP 通信。
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let httpMock: HttpTestingController;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
declarations: [AppComponent]
})
.compileComponents();
httpMock = TestBed.inject(HttpTestingController);
}));
这是一篇带有示例的好文章: Testing Angular HTTP Communication 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.