mardi 12 novembre 2019

Timeout - Async callback was not invoked JEST + MONGO + NESTJS

I´m make e2e testing with jest + mongodb atlas + nestjs. I have 3 suites test that usually pass but randomly someone of these 3 fail(all of test inner the suite)

The command for run my test are NODE_ENV=test jest --config ./test/jest-e2e.json --runInBand

First the code for beforeEach afterAll methods maybe can be relevant, ns not found occurr always dunno if this can be related.

export async function removeAllCollections() {
    const collections = Object.keys(mongoose.connection.collections);
    for (const collectionName of collections) {
        const collection = mongoose.connection.collections[collectionName];
        await collection.deleteMany({});
    }
}

export async function dropAllCollections() {
    const collections = Object.keys(mongoose.connection.collections);
    for (const collectionName of collections) {
        const collection = mongoose.connection.collections[collectionName];
        try {
            await collection.drop();
        } catch (error) {
            console.log(error);
            // Sometimes this error happens, but you can safely ignore it
            if (error.message === 'ns not found') { return; }
            // This error occurs when you use it.todo. You can
            // safely ignore this error too
            if (error.message.includes('a background operation is currently running')) {
                return;
            }
        }
    }
}

restaurant.e2e.test(will omit the mocking data variables)

const checkRestaurantsProperties = (body, expected) => {
    expect(body._id).toBeDefined();
    expect(body).toBeDefined();
    expect(body.name).toBeDefined();
    expect(body.name).toEqual(expected.name);
    expect(body.description).toBeDefined();
    expect(body.description).toEqual(expected.description);
    expect(body.menus).toBeDefined();
    expect(body.menus).toHaveLength(expected.menus.length);
    expect(body.menus).toEqual(expected.menus);
    expect(body.location).toBeDefined();
    expect(body.location).toEqual(expected.location);
    expect(body.type).toBeDefined();
    expect(body.type).toEqual(expected.type);
    expect(body.type).toHaveLength(expected.type.length);
    expect(body.creator).toBeDefined();
    expect(body.creator._id).toBeDefined();
    expect(body.creator._id).toEqual(userId);
    expect(body.creator.username).toBeDefined();
    expect(body.creator.username).toEqual(signupUser.username);
  };

  beforeAll(async (done) => {
    await mongoose.connect(
      'mongoatlasuri',
      { useNewUrlParser: true, useUnifiedTopology: true },
    );
    const testAppModule: TestingModule = await Test.createTestingModule({
      imports: [
        AppModule,
        GlobalModule,
        UsersModule,
        AuthModule,
        PetsModule,
        RestaurantsModule,
        ConfigModule,
      ],
      providers: [],
    }).compile();

    app = testAppModule.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ transform: true }));
    await app.init();
    done();
  });

  beforeEach(async (done) => {
    await removeAllCollections();
    const signupUserApp = await request(app.getHttpServer())
      .post('/users')
      .send(signupUser)
      .expect(HttpStatus.CREATED);
    const loginResponse = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: signupUser.email, password: signupUser.password })
      .expect(HttpStatus.CREATED);
    jwt = loginResponse.body.token;
    userId = loginResponse.body.user._id;
    done();
  });

  afterAll(async (done) => {
    await dropAllCollections();
    await mongoose.connection.close();
    await app.close();
    done();
  });

  it('POST should create a restaurant', async () => {
    const createRestaurant = await request(app.getHttpServer())
      .post('/restaurants')
      .set('Authorization', 'Bearer ' + jwt)
      .send(restaurant)
      .expect(({ body }) => {
        checkRestaurantsProperties(body, restaurant);
        expect(body.imageUrls).toBeDefined();
        expect(body.imageUrls).toEqual([]);
      })
      .expect(HttpStatus.CREATED);
    restaurantId = createRestaurant.body._id;
    return request(app.getHttpServer())
      .put('/restaurants/' + restaurantId + '/images')
      .set('Authorization', 'Bearer ' + jwt)
      .set('Content-Type', 'multipart/form-data')
      .attach('imageUrls', './test/koala.jpg')
      .expect(({ body }) => {
        checkRestaurantsProperties(body, restaurant);
        expect(body._id).toEqual(restaurantId);
        expect(body.imageUrls).toBeDefined();
        expect(body.imageUrls).toHaveLength(1);
      })
      .expect(HttpStatus.OK);
  });

  it('GET should retrieve a restaurant', async () => {
    const createRestaurant = await request(app.getHttpServer())
      .post('/restaurants')
      .set('Authorization', 'Bearer ' + jwt)
      .send(restaurant)
      .expect(HttpStatus.CREATED);
    restaurantId = createRestaurant.body._id;
    return request(app.getHttpServer())
      .get('/restaurants/' + restaurantId)
      .set('Authorization', 'Bearer ' + jwt)
      .expect(HttpStatus.OK);
  });

  it('GET should retrieve all restaurant', async () => {
    const createRestaurant = await request(app.getHttpServer())
      .post('/restaurants')
      .set('Authorization', 'Bearer ' + jwt)
      .send(restaurant)
      .expect(HttpStatus.CREATED);
    restaurantId = createRestaurant.body._id;
    return request(app.getHttpServer())
      .get('/restaurants')
      .set('Authorization', 'Bearer ' + jwt)
      .expect(({ body }) => {
        expect(body).toBeDefined();
        expect(body.restaurants).toHaveLength(1);
        checkRestaurantsProperties(body.restaurants[0], restaurant);
        expect(body.restaurants[0]._id).toEqual(restaurantId);
        expect(body.restaurants[0].imageUrls).toBeDefined();
        expect(body.restaurants[0].imageUrls).toHaveLength(0);
        expect(body.totalRestaurants).toBeDefined();
        expect(body.totalRestaurants).toEqual(1);
        expect(body.filterData).toBeDefined();
        expect(body.filterData.isFilterData).toBeDefined();
        expect(body.filterData.isFilterData).toEqual(false);
        expect(body.filterData.currentPage).toBeDefined();
        expect(body.filterData.currentPage).toEqual(1);
        expect(body.filterData.queryParams).toBeDefined();
        expect(body.filterData.queryParams).toBeNull();
      })
      .expect(HttpStatus.OK);
  });

  it('PUT should update a restaurant', async () => {
    const restaurantFinded: any = await RestaurantModel.find({ _id: restaurantId });
    const createRestaurant = await request(app.getHttpServer())
      .post('/restaurants')
      .set('Authorization', 'Bearer ' + jwt)
      .send(restaurant)
      .expect(({ body }) => {
        checkRestaurantsProperties(body, restaurant);
        expect(body.imageUrls).toBeDefined();
        expect(body.imageUrls).toEqual([]);
      })
      .expect(HttpStatus.CREATED);
    restaurantId = createRestaurant.body._id;
    return request(app.getHttpServer())
      .put('/restaurants/' + restaurantId)
      .set('Authorization', 'Bearer ' + jwt)
      .send(updatedRestaurant)
      .expect(({ body }) => {
        checkRestaurantsProperties(body, updatedRestaurant);
        expect(body._id).toEqual(restaurantId);
        expect(body.imageUrls).toBeDefined();
        expect(body.imageUrls).toHaveLength(0);
      })
      .expect(HttpStatus.OK);
  });
});

users.e2e.test

beforeAll(async (done) => {
        await mongoose.connect('mongoatalasUri',
            { useNewUrlParser: true, useUnifiedTopology: true });
        const testAppModule: TestingModule = await Test.createTestingModule({
            imports: [AppModule, GlobalModule,
                UsersModule,
                AuthModule,
                PetsModule,
                RestaurantsModule,
                ConfigModule],
            providers: [],
        }).compile();

        app = testAppModule.createNestApplication();
        app.useGlobalPipes(new ValidationPipe({ transform: true }));
        await app.init();
        done();
    });

    beforeEach(async (done) => {
        await removeAllCollections();
        const signupUserApp = await request(app.getHttpServer())
            .post('/users')
            .send(signupUser)
            .expect(HttpStatus.CREATED);
        const loginResponse = await request(app.getHttpServer())
            .post('/auth/login')
            .send({ email: signupUser.email, password: signupUser.password })
            .expect(HttpStatus.CREATED);
        jwt = loginResponse.body.token;
        userId = loginResponse.body.user._id;
        done();
    });

    // Disconnect Mongoose
    afterAll(async (done) => {
        await dropAllCollections();
        await mongoose.connection.close();
        await app.close();
        done();
    });

    it('GET should get all users', () => {
        return request(app.getHttpServer())
            .get('/users')
            .set('Authorization', 'Bearer ' + jwt)
            .expect(({ body }) => {
                expect(body).toBeDefined();
                expect(body[0].username).toBeDefined();
                expect(body[0].enabled).toBeDefined();
                expect(body[0].email).toBeDefined();
                expect(body[0].fullName).toBeDefined();
            })
            .expect(HttpStatus.OK);
    });

    it('GET should get a user by id', () => {
        return request(app.getHttpServer())
            .get('/users/' + userId)
            .set('Authorization', 'Bearer ' + jwt)
            .expect(({ body }) => {
                expect(body).toBeDefined();
                expect(body._id).toEqual(userId);
                expect(body.profile).toBeDefined();
                expect(body.fullName).toEqual(signupUser.fullName);
                expect(body.username).toEqual(signupUser.username);
                expect(body.lowercaseUsername).toEqual(signupUser.username.toLowerCase());
                expect(body.lowercaseEmail).toEqual(signupUser.email.toLowerCase());
            })
            .expect(HttpStatus.OK);
    });

    it('GET should reject get user by id bad request', () => {
        return request(app.getHttpServer())
            .get('/users/fakeid')
            .set('Authorization', 'Bearer ' + jwt)
            .expect(({ body }) => {
                expect(body.error).toBeDefined();
                expect(body.error).toEqual('Bad Request');
            })
            .expect(HttpStatus.BAD_REQUEST);
    });

    it('GET should reject get user by id user not found', () => {
        return request(app.getHttpServer())
            .get('/users/5da3532a3bb46805345d7479')
            .set('Authorization', 'Bearer ' + jwt)
            .expect(({ body }) => {
                expect(body.error).toBeDefined();
                expect(body.error).toEqual('Not Found');
                expect(body.message).toBeDefined();
                expect(body.message).toEqual('No user found!.');
            })
            .expect(HttpStatus.NOT_FOUND);
    });

    it('GET should get all restaurants of an user id', () => {
        return request(app.getHttpServer())
            .get('/users/' + userId + '/restaurants')
            .set('Authorization', 'Bearer ' + jwt)
            .expect(({ body }) => {
                expect(body).toBeDefined();
                expect(body).toHaveLength(0);
            })
            .expect(HttpStatus.OK);
    });

    it('PUT should update data and image related to user profile', async () => {
        const defineProfile = await request(app.getHttpServer())
            .put('/users/' + userId)
            .set('Authorization', 'Bearer ' + jwt)
            .send(updatedUser)
            .expect(({ body }) => {
                expect(body).toBeDefined();
                expect(body.web).toBeDefined();
                expect(body.web).toEqual('my websit');
                expect(body.description).toBeDefined();
                expect(body.description).toEqual('hi im description');
                expect(body.location).toBeDefined();
                expect(body.location).toEqual('location');
                expect(body.imageProfile).toBeDefined();
                expect(body.imageProfile).toEqual('');
            })
            .expect(HttpStatus.OK);
        return request(app.getHttpServer())
            .put('/users/' + userId + '/profileimage')
            .set('Authorization', 'Bearer ' + jwt)
            .set('Content-Type', 'multipart/form-data')
            .attach('imageProfile', './test/koala.jpg')
            .expect(({ body }) => {
                expect(body).toBeDefined();
                expect(body.fullName).toBeDefined();
                expect(body.fullName).toEqual(signupUser.fullName);
                expect(body.username).toBeDefined();
                expect(body.username).toEqual(signupUser.username);
                expect(body.lowercaseUsername).toBeDefined();
                expect(body.lowercaseUsername).toEqual(signupUser.username.toLowerCase());
                expect(body.lowercaseEmail).toBeDefined();
                expect(body.lowercaseEmail).toEqual(signupUser.email.toLowerCase());
                expect(body._id).toBeDefined();
                expect(body._id).toEqual(userId);
                expect(body.profile.web).toBeDefined();
                expect(body.profile.web).toEqual('my websit');
                expect(body.profile.description).toBeDefined();
                expect(body.profile.description).toEqual('hi im description');
                expect(body.profile.location).toBeDefined();
                expect(body.profile.location).toEqual('location');
                expect(body.profile.imageProfile).toBeDefined();
            })
            .expect(HttpStatus.OK);
    });

The error enter image description here

Aucun commentaire:

Enregistrer un commentaire