我有这个 Angular 组件,它可以发出简单的 http 请求:
import { CommonModule } from '@angular/common';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { Component, Input, OnInit } from '@angular/core';
@Component({
standalone: true,
imports: [CommonModule, HttpClientModule],
selector: 'http-requester',
template: '',
})
export class HttpRequesterComponent implements OnInit {
@Input() url!: string;
constructor(private httpClient: HttpClient) {}
ngOnInit(): void {
this.httpClient.get(this.url).subscribe((content) => console.log(content));
}
}
这个测试:
import {
HttpClientTestingModule,
HttpTestingController,
} from '@angular/common/http/testing';
import { Spectator, createComponentFactory } from '@ngneat/spectator';
import { HttpRequesterComponent } from './http-requester.component';
describe('HttpRequesterComponent', () => {
let spectator: Spectator<HttpRequesterComponent>;
let httpTestingController: HttpTestingController;
const createComponent = createComponentFactory({
component: HttpRequesterComponent,
imports: [HttpClientTestingModule],
});
beforeEach(() => {
spectator = createComponent();
httpTestingController = spectator.inject(HttpTestingController);
});
afterEach(() => {
httpTestingController.verify();
});
it('should call httpClient.get with the provided URL', () => {
const url = 'https://example.com';
spectator.component.url = url;
spectator.detectChanges();
const request = httpTestingController.expectOne(url);
request.flush('Content here');
});
});
然而,测试总是失败,并在
expectOne
调用中显示“预期有一个针对条件“匹配 URL:https://example.com”的匹配请求,但没有找到”。
任何人都可以帮我找出原因吗?
我想
spectator.detectChanges();
打电话给ngOnInit();
但也许不是。
尝试像这样显式调用它:
it('should call httpClient.get with the provided URL', () => {
const url = 'https://example.com';
spectator.component.url = url;
spectator.detectChanges();
// !! explicitly call ngOnInit and see if that works.
spectator.component.ngOnInit();
console.log('Expecting http call !!');
const request = httpTestingController.expectOne(url);
request.flush('Content here');
});
另外,将日志添加到
ngOnInit()
以查看是否被调用。
ngOnInit(): void {
// make sure the below line is called ensuring that ngOnInit was called
// and make sure it was called before Expecting http call!! from the test
console.log('ngOnInit called !!');
this.httpClient.get(this.url).subscribe((content) => console.log(content));
}