hapi icon indicating copy to clipboard operation
hapi copied to clipboard

Any way to wait for `response` event to fire after calling `inject()`?

Open createthis opened this issue 4 years ago • 2 comments

Is there any way to wait for response event to fire after calling inject()? In my testing, response events seem to fire asynchronously after inject() which makes testing them extremely difficult from tests. I have to disable them in my test environment in order to avoid race conditions.

createthis avatar Aug 09 '21 20:08 createthis

It would be useful to see the code that you're writing that is giving you issues. In the hapi test suite you'll often see code like this, making use of hapi events async support: https://github.com/hapijs/hapi/blob/c95985e225fa09c4b640a887ccb4be46dbe265bc/test/request.js#L972-L978

Hopefully this helps!

devinivy avatar Aug 12 '21 15:08 devinivy

It would be useful to see the code that you're writing that is giving you issues. In the hapi test suite you'll often see code like this, making use of hapi events async support: [...]

Hopefully this helps!

I see I didn't specify the method I'm calling. Apologies. I'm using:

server.events.on('response', callback);

I do see that Podium.once() returns Teamwork.Team.work, which is indeed a promise: https://github.com/hapijs/teamwork/blob/1c07fbae35f344268f7eb6966c302a6ce874b97b/lib/index.js#L21

...but I don't see Teamwork being used in Podium.on().

To clarify, I'd like to be able to do something like this in a test:

server.events.on('response', callback);
await server.inject(request);
// 1. Wait for any pending `response` events to finish executing
// 2. Reset my database

Currently, I'm experiencing "heisenbugs" because there is a race condition between 1 and 2, above. Sometimes I reset the database in 2, and then the response callback from 1 fires, attempting to use a non-existant database table.

I've worked around this issue for the moment by disabling all of my response on listeners in the test environment, but this is less than ideal.

createthis avatar Aug 12 '21 16:08 createthis