HttpTestingController.expectOne看不到我的请求,但是在afterEach()方法中打开了它

时间:2019-10-25 10:31:11

标签: angular unit-testing karma-jasmine

我正在编写一个单元测试来测试正在调用rest API的服务。 ExpectOne()找不到我的请求:预期条件“ Match URL:http://localhost:5000/api/v1.0/stat/estimation-graph”的一个匹配请求,找不到。

我尝试了ExpectOne()的不同重载,例如:

yaml

我还尝试更改URL,使其包含参数('http://localhost:5000/api/v1.0/stat/estimation-graph?battleCount=100&winCount=50'),但没有运气。

最后,我打开了一个带有Karma测试结果的Chrome控制台,但由于CORS政策,我发现无法调用我的API。我也解决了。

我的.spec.ts文件:

daemonset

我的服务等级:

httpMock.expectOne(url)
httpMock.expectOne({method: 'GET', url: url})
httpMock.expectOne(res => res.method === 'GET' && res.url === url)

“业力”结果窗口告诉我无法找到打开的请求:


// imports..

describe('StatProviderService', () => {
    let injector: Injector;
    let httpMock: HttpTestingController;
    let statService: StatProviderService;
    beforeEach(() => 
    {
        injector = TestBed.configureTestingModule({
            imports: [
                HttpClientModule,
                HttpClientTestingModule,
            ],
            providers: [
                StatProviderService,
            ],
        });
        httpMock = injector.get(HttpTestingController);
        statService = injector.get(StatProviderService);
    });

    afterEach(() => {
        httpMock.verify();
    });

    it('should work', () => {
        let response;
        let url = 'http://localhost:5000/api/v1.0/stat/estimation-graph';

        statService.getEstimationGraphData( 100, 50 )
          .subscribe(res => {
            response = res;
          });

        const req = httpMock.expectOne(url);
        req.flush(response);
    });
});

但是 afterEach()中添加了 httpMock.verify()之后,出现了下一个错误:


// imports...

@Injectable({
    providedIn: 'root'
})
export class StatProviderService {
    // private variables

    constructor(
        private http: HttpClient
    ) { }

    private baseApiUrl(endpoint?: string) {
        return `${this.env.apiUrl}/${this.apiVer}/${endpoint}`;
    }

    getEstimationGraphData(battlecount: number, winCount: number): Observable<IEstimationGraphPoint[]> {
        return this.http.get<IEstimationGraphPoint[]>(`${this.baseApiUrl(this.graphDataEndpoint)}/?battleCount=${battlecount}&winCount=${winCount}`);
    }
}

所以看起来请求被调用了,但是晚于预期。就我订阅了 getEstimationGraphData()而言,应该同步调用它,对吧?

1 个答案:

答案 0 :(得分:0)

由于您要在服务中向URL附加参数,因此HttpTestingController希望测试URL也包含参数。不用在服务中创建带有参数的URL,而应将它们作为HttpParams传递。

getEstimationGraphData(battlecount: number, winCount: number): Observable<IEstimationGraphPoint[]> {
  return this.http.get<IEstimationGraphPoint[]>(this.baseApiUrl(this.graphDataEndpoint), {
    params: {
      battleCount: battlecount.toString(),
      winCount: winCount.toString()
    }
  });
}

现在,在您的spec文件中,您需要使用自定义函数来检查url。使用以下代码测试网址:

const req = httpMock.expectOne((request: HttpRequest<any>) => {
  return request.url === url;
});

request.url将包含不带参数的url。如果您还需要检查这些参数,则带有参数的实际URL将在request.urlWithParams中。

您可能还需要从规格文件中删除HttpClientModule。您只需要HttpClientTestingModule