推荐答案
// www.javascriptcn.com code example
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});本题详细解读
1. 安装依赖
首先,确保你已经安装了 @nestjs/testing 和 supertest 依赖:
npm install --save-dev @nestjs/testing supertest
2. 创建测试模块
在测试文件中,使用 Test.createTestingModule 创建一个测试模块。这个模块通常会导入你的应用模块(如 AppModule),以便在测试中使用。
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();3. 初始化应用
通过 moduleFixture.createNestApplication() 创建一个 Nest.js 应用实例,并调用 app.init() 来初始化应用。
app = moduleFixture.createNestApplication(); await app.init();
4. 编写测试用例
使用 supertest 来发送 HTTP 请求并验证响应。request(app.getHttpServer()) 会返回一个 supertest 的请求对象,你可以使用它来发送 GET、POST 等请求。
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});5. 清理资源
在测试结束后,确保关闭应用以释放资源。
afterAll(async () => {
await app.close();
});6. 运行测试
使用你喜欢的测试运行器(如 Jest)来运行测试:
npm test
通过以上步骤,你可以使用 supertest 对 Nest.js 应用进行端到端(e2e)测试。