I have a few Jest tests that are passing when run individually but are failing when run together. As far as I can tell the tests are self contained but they must be interacting in some way that I'm missing.
The tests are testing a connection adaptor that tries to connect to a BLE device multiple times while only returning a single pending connection that can be awaited or cancelled.
Here are the tests:
test("connect returns pending connection", async () => {
const adaptor = new MockAdaptor();
const pendingConnection = adaptor.connect("test");
expect(pendingConnection.id).toBe("test");
await pendingConnection.cancel();
})
test('connect success', async () => {
const adaptor = new MockAdaptor();
const pendingConnection = adaptor.connect("test");
// TEST FAILING HERE
const connection = await pendingConnection.connectionPromise as any;
expect(connection).toBe("test");
})
Here is the code shared by the tests:
const getSuccessfulPendingConnection = () => ({
address: "test",
connectionPromise: new Promise((resolve, _) => {
setTimeout(() => resolve("test"), 1000)
}),
cancel: async () => {}
})
const getFailedPendingConnection = () => ({
address: "test",
connectionPromise: new Promise((_, reject) => {
setTimeout(() => reject("connect failed"), 1000);
}),
cancel: async () => {}
})
const getMockPendingConnection = (id: string) => {
if(id === "test") {
return getSuccessfulPendingConnection();
}
return getFailedPendingConnection();
}
class MockAdaptor {
connect(id: string) {
let rejectPromise = () => {};
let cancelConnection = async () => {};
let connectionCancelled = false;
const connectionPromise = new Promise(async (resolve, reject) => {
rejectPromise = () => {
reject("Connection cancelled")
connectionCancelled = true;
};
let newConnection = undefined;
while(!connectionCancelled) {
try {
const pendingConnection = getMockPendingConnection(id);
cancelConnection = pendingConnection.cancel;
newConnection = await pendingConnection.connectionPromise;
return resolve(newConnection);
} catch (error) {
console.log('Connection failed', error);
}
}
});
const cancel = async () => {
rejectPromise();
await cancelConnection();
}
return {
id,
connectionPromise,
cancel,
}
}
}
When I run these tests together, 'connect returns pending connection' passes, but 'connect success' fails with the message "Connection cancelled".