Angular中进行Jest服务API调用时,返回总是执行catch块
创始人
2024-10-31 14:02:03
0

在进行Jest服务API调用时,需要将返回值转换为Promise对象。这可以通过使用RxJS中的toPromise()方法来实现。具体代码示例如下:

import { TestBed } from '@angular/core/testing';
import { ApiService } from './api.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('ApiService', () => {
  let httpTestingController: HttpTestingController;
  let service: ApiService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ApiService]
    });
    httpTestingController = TestBed.inject(HttpTestingController);
    service = TestBed.inject(ApiService);
  });

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

  it('should return data successfully', async () => {
    const testData = {
      name: 'test',
      age: 20
    };
    service.getData().toPromise().then((data) => {
      expect(data).toEqual(testData);
    }).catch(err => {
      fail('Should not return error');
    });
    const req = httpTestingController.expectOne('/api/data');
    req.flush(testData);
  });

  it('should return error', async () => {
    service.getData().toPromise().then((data) => {
      fail('Should return error');
    }).catch(err => {
      expect(err.status).toEqual(404);
    });
    const req = httpTestingController.expectOne('/api/data');
    req.flush('Not found', { status: 404, statusText: 'Not found' });
  });
});

在这个示例中,我们使用了Jest进行单元测试,对一个名为ApiService的服务进行测试。我们期望该服务能够成功地获取数据并返回给我们。我们在代码中使用了toPromise()方法将返回值转换为Promise对象,并使用了async/await来等待API返回数据。

如果API调用成功,则会进入then块,并测试数据是否正确。如果API调用失败,则会进入catch块,并测试错误状态码是否为404。

使用toPromise()方法将返回值转换为Promise对象将使得我们可以使用async/await来等待API返回数据。这样,我们就可以在测试用例中测试API调用是否正确。

通过这样的方式,我们可以在Angular应用中更轻松地测试API调用,并保证代码的稳定性。

相关内容

热门资讯

安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
安装安卓应用时出现“Play ... 在安装安卓应用时出现“Play Protect 警告弹窗”的原因是Google Play Prote...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安卓系统怎么连不上carlif... 安卓系统无法连接CarLife的原因及解决方法随着智能手机的普及,CarLife这一车载互联功能为驾...
本地化字符串和默认值 本地化字符串是指将应用程序中的文本内容根据不同的语言和地区进行翻译和适配的过程。当应用程序需要显示不...
iqoo安卓14系统怎么升级系... 亲爱的iQOO手机用户们,是不是觉得你的手机系统有点儿落伍了呢?别急,今天就来手把手教你如何升级到最...
iwatch怎么连接安卓系统,... 你有没有想过,那款时尚又实用的iWatch,竟然只能和iPhone好上好?别急,今天就来给你揭秘,怎...
windows安装系统退不出来... Windows安装系统退不出来的解决方法详解在电脑使用过程中,有时会遇到在安装Windows系统时无...