在单元测试Nest.js中测试抛出新的HttpException,可以按照以下步骤进行:
@nestjs/testing
。app.service.spec.ts
,并导入相关的模块和依赖项:import { Test, TestingModule } from '@nestjs/testing';
import { AppService } from './app.service';
import { HttpException } from '@nestjs/common';
describe('AppService', () => {
let appService: AppService;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
providers: [AppService],
}).compile();
appService = app.get<AppService>(AppService);
});
describe('yourTestFunction', () => {
it('should throw HttpException', () => {
expect(() => {
appService.yourTestFunction();
}).toThrow(HttpException);
});
});
});
AppService
中定义一个需要测试的函数yourTestFunction
,并在该函数中抛出HttpException
:import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
@Injectable()
export class AppService {
yourTestFunction() {
throw new HttpException('Your error message', HttpStatus.BAD_REQUEST);
}
}
$ npm run test
HttpException
。这样,你就可以在Nest.js的单元测试中测试抛出新的HttpException
了。
关于Nest.js的单元测试和异常处理的更多信息,你可以参考腾讯云的相关文档和产品:
领取专属 10元无门槛券
手把手带您无忧上云