Nest.js控制器测试中如何对返回的状态码做断言?
问题原因
你当前的测试有两个核心问题:
check方法依赖注入了@Res()响应对象,你调用方法时没有传入这个对象,根本无法执行到response.status(200).send()逻辑- 你直接把
controller.check()的返回值和字符串test做断言,但是你的check方法没有任何返回值,这个断言逻辑完全不匹配需求
正确的单元测试写法
我们直接 mock 一个响应对象传入 check 方法,监听 status 和 send 方法的调用即可:
import { Test, TestingModule } from '@nestjs/testing'; import { TestController } from './test.controller'; describe('TestController', () => { let controller: TestController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [TestController], }).compile(); controller = module.get<TestController>(TestController); }); describe('check', () => { it('should return status 200', async () => { // 构造mock响应对象 const mockResponse = { status: jest.fn().mockReturnThis(), // mock status方法,返回自身支持链式调用 send: jest.fn() // mock send方法 }; // 把mock的响应对象传入check方法 await controller.check(mockResponse); // 断言status方法被传入了200参数 expect(mockResponse.status).toHaveBeenCalledWith(200); // 可选:断言send方法被调用 expect(mockResponse.send).toHaveBeenCalled(); }); }) });
更贴近真实请求的端到端测试写法
如果需要模拟真实HTTP请求验证状态码,可以使用supertest工具实现:
import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import * as request from 'supertest'; import { TestController } from './test.controller'; describe('TestController (e2e)', () => { let app: INestApplication; beforeEach(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ controllers: [TestController], }).compile(); app = moduleFixture.createNestApplication(); await app.init(); }); it('/test (GET) returns 200', () => { return request(app.getHttpServer()) .get('/test') .expect(200); // 直接断言返回状态码为200 }); afterEach(async () => { await app.close(); }); });
内容的提问来源于stack exchange,提问作者Take
相关产品推荐
相关产品推荐

