LoginSignup
10
0

Nest.js で Jest を使った E2E テストのエラー解消方法

Last updated at Posted at 2023-05-28

以下のエラーはいろんなケースで発生する

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  TCPWRAP
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From domain/common/constants/constants.e2e-spec.ts.

      at Object.getCodec (../node_modules/mysql2/node_modules/iconv-lite/lib/index.js:63:27)
      at Object.getDecoder (../node_modules/mysql2/node_modules/iconv-lite/lib/index.js:125:23)
      at Object.<anonymous>.exports.decode (../node_modules/mysql2/lib/parsers/string.js:10:25)
      at Packet.readNullTerminatedString (../node_modules/mysql2/lib/packets/packet.js:412:25)
      at Function.fromPacket (../node_modules/mysql2/lib/packets/handshake.js:62:33)
      at ClientHandshake.handshakeInit (../node_modules/mysql2/lib/commands/client_handshake.js:98:40)
      at ClientHandshake.execute (../node_modules/mysql2/lib/commands/command.js:45:22)
      at PoolConnection.handlePacket (../node_modules/mysql2/lib/connection.js:456:32)
      at PacketParser.onPacket (../node_modules/mysql2/lib/connection.js:85:12)
      at PacketParser.executeStart (../node_modules/mysql2/lib/packet_parser.js:75:16)
      at Socket.<anonymous> (../node_modules/mysql2/lib/connection.js:92:25)

なので、今後もどんなケースで上記が発生するかを追記していこうと思う。

1. 不要なクラスを読み込んでいた

動作確認をするためにいろいろいじっていた際にファイルを削除し忘れていた。

.module.js
@Module({
  controllers: [HogeController],
  imports: [
    TypeOrmModule.forFeature(
      [XXX, YYY]
    )
  ],
  providers: [
    HogeService,
    NeedlessService // これを削除
  ],
})

2. Mockができていない

外部サービスにリクエストをとばすメソッドなどのMockがうまくいってない場合

.e2e.ts
  let app: INestApplication;
  const mockS3Service: MockType<S3Service> = {
    getPreSignedUrlForPut: jest.fn().mockResolvedValue({url: 'url'})
  };

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        ...buildDefaultImportedItems(), //テスト用の自作メソッド
        //FilesModule, ここでモジュールを読み込まずに
      ],
      controllers: [FilesController], // テスト対象のコントローラを読み込む
      providers: [
        {
          provide: S3Service,
          useValue: mockS3Service,
        },
      ],
    }).compile();

    app = await initApp(app, moduleFixture); //テスト用の自作メソッド
  });
10
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
0