I've written some integration test using Jest, Supertest, Moongose. I run all test isolated (test.only) and they work but sometimes don't. Often this happens when I run the entire test suite. I give you an example: This test creates a new registry in a MongoDB collection and then other test use this new registry to perform another operations:
beforeAll(async () => {
await mongoose.connect(config.mongoose.url, config.mongoose.options);
});
afterAll(async () => {
await mongoose.disconnect();
await new Promise(resolve => setTimeout(() => resolve(), 500));
});
let credentials = [];
let fechaHora = [];
// generate a new Id registry
// generate credentials
// generate date and hour
beforeEach(async () => {
rooms.insertRoomsToFile(rooms.getNewIdRoom() + '|');
_idRoom = rooms.getIdRoom();
credentials = await rooms.generateCredentialsBE(_idOrganization, basicToken);
fechaHora = rooms.generateRoomDateAndHour();
});
test(`endpoint ${BASE_URL}${registerMeetingRoute} : 200 OK (Happy Path)`, async () => {
generatedIdRoom = _idRoom;
const data = {
idOrganization: 1,
idRoom: generatedIdRoom,
date: fechaHora[0],
hour: fechaHora[1],
attendes: [
{
email: "[email protected]",
id: 1,
firstName: "John",
lastName: "Doe",
userAttende: "10000000-0000-0000-0000-000000000000",
rol: 1,
telephone: "5555555555"
},
{
email: "[email protected]",
id: 2,
firstName: "Tom",
lastName: "Taylor",
userAttende: "20000000-0000-0000-0000-000000000000",
rol: 2,
telephone: "5555555556"
}
]
};
const encryptedData = await rooms.encrypt(data);
idAccess = encryptedData.idAccess;
await request(app)
.post(`${BASE_URL}${registerMeetingRoute}`)
.set('content-type', 'application/json')
.set('authorization', 'Bearer ' + credentials[2])
.set('x-accessId', idAccess)
.send(encryptedData)
.expect(200);
rooms.saveLog(JSON.stringify(encryptedData), `endpoint ${BASE_URL}${registerMeetingRoute} : 200 OK (Happy Path)`);
});
This works fine, the problem is sometimes don't. I've tried many answers here and read blogs about this topic but I can't solve it. I tried:
- Increase testTimeout property in jest.config.js
- Open and close MongoDb connection per test
- To use mongodb-memory-server
- --runInBand option
Thanks in advance :)