You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jest测试NestJs服务中抛出异常的函数?

NestJS 中使用 Jest 测试服务类抛异常的方法

前置准备

首先确保你已在测试文件中导入必要依赖,且完成测试模块初始化,拿到 MyService 的实例。

测试用例编写

对于同步抛出异常的方法,Jest 提供了toThrow匹配器来验证异常抛出行为,注意需要将待测方法的调用包裹在匿名函数中,避免异常在断言执行前抛出导致测试直接失败。
完整测试代码示例如下:

import { Test, TestingModule } from '@nestjs/testing';
import { UnprocessableEntityException } from '@nestjs/common';
import { MyService } from './my.service'; // 替换为你的服务实际路径

describe('MyService', () => {
  let service: MyService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [MyService],
    }).compile();

    service = module.get<MyService>(MyService);
  });

  it('should throw UnprocessableEntityException with expected message', () => {
    const testMsg = '自定义错误信息';
    // 校验抛出的异常类型
    expect(() => service.throwError(testMsg)).toThrow(UnprocessableEntityException);
    // 校验抛出的异常信息
    expect(() => service.throwError(testMsg)).toThrow(testMsg);
  });
});

补充说明

  • 如果要测试异步方法抛出异常,需要搭配rejects和await使用:
    await expect(service.asyncThrowError(testMsg)).rejects.toThrow(UnprocessableEntityException);
    
  • 如果需要对异常实例做更复杂的校验,可以用try/catch包裹调用逻辑,在catch块中对异常实例做断言。

内容的提问来源于stack exchange,提问作者Leonardo Schmitt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:15:02