NestJs e Jest: la richiesta in attesa genera 404
Attualmente sto cercando di ottenere l'oggetto risposta di una richiesta di "supertest".
Se chiamo get senza wait, ottengo un httpCode 200, ma senza corpo:
import { Test, TestingModule } from '@nestjs/testing';
import { AuthModule } from './auth.module';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
describe('AuthService', () => {
let app: INestApplication;
beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthModule]
}).compile();
app = module.createNestApplication();
await app.init();
});
it('should be defined', async () => {
const res = request(app.getHttpServer())
.get('/')
.expect(200);
});
afterAll(async () => {
app.close();
});
});
Jest mi dà il seguente risultato. Ma non posso riferirmi a res.body
AuthService
√ should be defined (5ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 15.961s, estimated 16s
Ora, se cambio la chiamata get in una chiamata asincrona:
it('should be defined', async () => {
const res = await request(app.getHttpServer())
.get('/')
.expect(200);
});
Ottengo un risultato del test fallito:
AuthService
× should be defined (35ms)
● AuthService › should be defined
expected 200 "OK", got 404 "Not Found"
at Test.Object.<anonymous>.Test._assertStatus (node_modules/supertest/lib/test.js:268:12)
at Test.Object.<anonymous>.Test._assertFunction (node_modules/supertest/lib/test.js:283:11)
at Test.Object.<anonymous>.Test.assert (node_modules/supertest/lib/test.js:173:18)
at Server.localAssert (node_modules/supertest/lib/test.js:131:12)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Senza la chiamata asincrona, non posso fare riferimento al corpo. Ma ottengo ogni volta un 404, sulla stessa funzione get. Appena usato wait per la chiamata asincrona.
Risposte
Il test senza async viene superato solo perché il test termina prima dell'esecuzione dell'asserzione expect(200)
. In entrambi i casi, la chiamata /
restituirà un errore 404.
Il problema principale è che stai dichiarando un modulo un provider, invece di importarlo:
await Test.createTestingModule({
// should be imports instead of providers
providers: [AuthModule]
})
Perché stai configurando il tuo AuthModule
separatamente dal resto della tua applicazione? Ti consiglierei di testare il tuo test unitario in separazione (includere solo il provider che viene testato, simulare tutto il resto) e testare l'intera applicazione nei test e2e (solo simulare parti distinte della tua app se necessario, ad esempio, chiamate API a 3rd- servizi per feste); vedere questo thread per maggiori dettagli.
Suggerirei di importare AppModule
invece:
const module: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile();