超时-未调用异步回调JEST + MONGO + NESTJS

时间:2019-11-12 23:34:15

标签: mongodb testing mongoose jestjs nestjs

我正在使用jest + mongodb atlas + nestjs进行e2e测试。我有3个通常可以通过的套件测试,但随机地这3个套件中的某人失败了(套件内部的所有测试)

运行我的测试的命令是NODE_ENV = test jest --config ./test/jest-e2e.json --runInBand

首先,beforeEach afterAll方法的代码可能是相关的,如果可以相关,则找不到ns总是不知道。

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(将省略模拟数据变量)

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);
    });

错误 enter image description here

0 个答案:

没有答案