如何在Angular 9中测试tomise [英] How to test toPromise in Angular 9

查看:45
本文介绍了如何在Angular 9中测试tomise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下功能编写单元测试

I am trying to write unit test for the following function

    public loadValues(): Promise<any> {

      return this._http.get(this.url)
         .toPromise()
         .then((values: any) => {
            this.values = values;
         })
     }

APP_INITIALIZER调用此函数,这就是它返回promise而不是可观察的原因.我没有找到任何要测试Promise的文章,我们将不胜感激.

This function is called by the APP_INITIALIZER and thats the reason it is returning a promise instead of observable. I did not find any article to test toPromise, any help will be appreciated.

我为此编写了以下测试

it('should return app values', async () => {
    const mockValues = {test: 123};
    spyOn(httpClient, 'get').and.returnValue(of(mockValues)).and.callThrough();
    await service.loadValues();
    expect(service.values).toEqual(mockValues);

    const req = httpMock.expectOne(TEST_URL);
    expect(req.request.method).toBe('GET');
});

推荐答案

我也来完成为toPromise函数创建单元测试的类似任务.我翻阅了几篇文章,但没有发现这件事.解决方案:toPromise等待可观察对象完成.所以我们必须完成测试中的可观察性.我希望这种解决方案对您有用.

I too came also similar task of creating unit tests for the toPromise function. I looked across several articles nowhere I found this thing mentioned. Solution: toPromise waits for the observable to complete. so we have to complete the observable in the tests. I hope this solution works for you.

it('should return app values', fakeAsync () => {
    const mockValues = {test: 123};
    const mockSubject = new Subject<any>(); // create subject of your object type
    spyOn(httpClient, 'get').and.returnValue(mockSubject.asObservable());
    await service.loadValues();
    mockSubject.next(mockValues);
    mockSubject.complete();
    tick();
    expect(service.values).toEqual(mockValues);

    const req = httpMock.expectOne(TEST_URL);
    expect(req.request.method).toBe('GET');
});

这篇关于如何在Angular 9中测试tomise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆