NestJsとJest:リクエストが404をスローするのを待つ

Aug 24 2020

私は現在、「スーパーテスト」リクエストの応答オブジェクトを取得しようとしています。

待機せずにgetを呼び出すと、httpCode 200を取得しますが、本文はありません。

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は私に次の出力を与えます。しかし、私は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

ここで、get呼び出しを非同期呼び出しに変更すると、次のようになります。

  it('should be defined', async () => {
const res = await request(app.getHttpServer())
  .get('/')
  .expect(200);

});

失敗したテスト結果が表示されます:

  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

非同期呼び出しがないと、本文を参照できません。しかし、同じget関数で404を毎回取得します。非同期呼び出しを待つために使用されました。

回答

1 KimKern Aug 26 2020 at 01:55

非同期なしのテストは、アサーションexpect(200)が実行される前にテストが終了したためにのみ合格します。どちらの場合も、呼び出し/は404エラーを返します。

主な問題は、モジュールをインポートするのではなく、プロバイダーとして宣言していることです。

await Test.createTestingModule({
  // should be imports instead of providers
  providers: [AuthModule]
})

AuthModuleアプリケーションの他の部分とは別に設定するのはなぜですか?単体テストを個別にテストし(テストされるプロバイダーのみを含め、他のすべてをモックする)、e2eテストでアプリケーション全体をテストすることをお勧めします(必要に応じて、アプリの個別の部分のみをモックします。たとえば、3番目のAPI呼び出し-パーティーサービス); 詳細については、このスレッドを参照してください。

AppModule代わりにインポートすることをお勧めします:

const module: TestingModule = await Test.createTestingModule({
  imports: [AppModule]
}).compile();