我目前正在使用 Jest 对 NestJS 应用程序进行端到端测试,并且在测试环境设置方面遇到了问题。我正在利用 supertest 进行 HTTP 断言,并且我的模板是使用 hbs 渲染的。
以下是我正在使用的软件包的版本:
NestJS: 10
supertest: 6.3
Jest: 29.5
hbs: 4.2
当我使用 node run test:e2e 运行 e2e 测试时,会发生错误。但是,当我正常运行该应用程序时,一切正常。 这是我的
main.ts
:
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.setBaseViewsDir(join(__dirname, '..', 'views'));
app.setViewEngine('hbs');
await app.listen(3000);
}
bootstrap();
这是
app.controller.ts
:
@Get()
@Render('index')
root() {
return { message: 'Hello world!' };
}
我的
app.e2e-spec.ts
:
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
为了让测试环境识别视图引擎,我需要做任何额外的设置吗? 预先感谢
您在
app.setViewEngine()
函数中调用了 bootstrap
,但没有在测试套件文件中调用引导函数。我不明白为什么你期望它能起作用
我想你只需要将
app.setViewEngine()
添加到你的 app.e2e-spec.ts
中
就像 Micael Levi 所建议的那样,我通过添加
setViewEngine()
调用来实现此功能:
// Replace INestApplication with NestExpressApplication
let app: NestExpressApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
app.setViewEngine('hbs'); // <-- add template engine
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect(/Hello World!/); // <-- use regex to match part of output
});