serhii kuzmych
serhii kuzmych

Reputation: 385

jest calls afterEach (teardown) before test finish only in debug mode

I am using nodejs, nestjs, supertest, mongodb, mongoose. My tests run is completed successfully, using command npm run test:e2e from default nestjs package.json config. When I execute my separate test in debug mode, from vscode debug view it fails with error of disposed mongodb connection. The test has mutliple async requests calls which I await it returns after request is called and starts executing jest teardown afterEach and afterAll which is kinda strange for me.

My launch.json

    {
      "type": "node",
      "request": "launch",
      "name": "Jest Current File e2e tests",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": [
        "${fileBasenameNoExtension}",
        "--config",
        "${workspaceFolder}/test/jest-e2e.json"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "disableOptimisticBPs": true,
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest"
      }
    }

jest-e2e.json

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  }
}

app.e2e-spec.ts


describe('app (e2e)', () => {
  let app: INestApplication;
  let connection: Connection;
  let dbInitializer: DbInitializer;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await createAndCompileTestingModule();

    app = moduleFixture.createNestApplication();

    await configApp(app);

    await app.init();
  });

  afterAll(async () => {
    await app.close();
  });

  beforeEach(async () => {
    const configService = app.get(ConfigService);
    const logger = new MyLogger(configService);
    connection = app.get(CustomConnectionService).getConnection();
    dbInitializer = new DbInitializer(connection, logger);
    await dbInitializer.seedDb();
  });

  afterEach(async () => {
    await connection.db.dropCollection(dbInitializer.articleCollectionName);
    await connection.db.dropCollection(dbInitializer.userCollectionName);
  });

  it('/ (POST) creates article', async function () {
    expect.assertions(9);
    const userToLogin = {
      username: 'leane1Gra',
      password: 'cft0id32',
    };

    const httpServer = app.getHttpServer();

    const responseLogin = await request(httpServer)
      .post(`/${LoginEndPoint}`)
      .set('Accept', 'application/json')
      .send(userToLogin);

    expect(responseLogin.statusCode).toBe(201);

    const userLoginResponse = responseLogin.body as UserLoginResponse;

    const resposeGetUser = await request(app.getHttpServer())
      .get(`/${UsersEndpoint}/by-username`)
      .query({ username: userToLogin.username });

    expect(resposeGetUser.statusCode).toBe(200);

    const userFindByUsernameResponse =
      resposeGetUser.body as MappedUserResponse;

    const articleToCreate = {
      title: 'article a',
      subtitle: 'subtitle a',
      description: 'description a',
      category: 'history',
      ownerId: userFindByUsernameResponse.id,
    };

    const response = await request(httpServer)
      .post(`/${ArticlesEndpoint}`)
      .set('Authorization', `Bearer ${userLoginResponse.user_jwt}`)
      .set('Accept', 'application/json')
      .send(articleToCreate);

    expect(response.statusCode).toBe(201);
    expect(response.headers['content-type']).toMatch(/json/);

    const { updatedUser, newArticle } = response.body as CreateArticleResponse;

    expect(newArticle.id).toBeTruthy();
    expect(newArticle.title).toBe(articleToCreate.title);

    expect(updatedUser.id).toBeTruthy();
    expect(updatedUser.articleIds).toContain(newArticle.id);
    expect(updatedUser.numberOfArticles).toBe(
      userFindByUsernameResponse.numberOfArticles + 1,
    );
  });

}

I am adding a video of test run in debug mode

enter image description here

Upvotes: 2

Views: 1062

Answers (1)

serhii kuzmych
serhii kuzmych

Reputation: 385

Add the timeout after your it test. The max value for timeout is 32 bit signed integer. You can debug your test during specified timeout without jest teardown called.

it('/ (POST) creates article', async function () {
// test body omitted
},147483647)

Upvotes: -1

Related Questions