While working on building an integration test in jest, I encountered a situation where the product being tested would call into a callback "at some point". The code under test is initiated by calling an event over an rpc "connection" (which is mocked out to use in-memory messages), but the connection notification API returns immediately instead of waiting for all asynchronous processes to finish.
The setup looks something like this:
test.tsx
//...preamble...
it('fire and forget with callback', async () => {
const receivedRequests = [];
clientConnection.onRequest(requestData => {
receivedRequests.push(requestData);
if (receivedRequests.length == 5) {
signal.release();
}
});
clientConnection.sendNotification(usefulTestData);
// wait for a signal on
await signal.waitAsync();
expect(receivedRequests).toEqual(expectedTestDataArrFromFile);
});
server.tsx
// ...preamble...
Server() {
// ...
//onNotification handler callback's return type is void, not Promise
this.connection.onNotification((notificationData) => this.handleNotification(notificationData));
private async function handleNotification(data) {
// do something interesting
await this.connection.sendRequest(requestData);
// do more...
}
In this scenario, the connection
object on both ends are different objects communicating through a mocked-out RPC. The sendNotification
method on the client connection eventually triggers the onNotification
method on the server side, and vice versa.
Without altering the contract, is there a way to create a signal in the callback that will only allow the test to continue executing conditionally?