I've been using the following pattern to test conditions after state updates in my components using react
.
await expect(new Promise((resolve) => {
let intervalId = setInterval(() => {
component.update();
if (myCondition) {
clearInterval(intervalId);
resolve(true);
}
}, 25);
})).resolves.toBe(true);
This works well and is guaranteed to work but it's a pain to write and quite verbose.
I've been looking into possibly using setImmediate
rather than setInterval
. This would prevent the polling (and allows me to test negative assertions which currently aren't possible without introducing another level of verbosity with a try
/catch
), but is it guranteed to work with react
async mechanisms such as setState
?
For example what happens if react
decides to batch try to batch some setState events together or something along those lines and setImmediate
gets put in the event loop queue before react
dispatches the state update actions?
I don't want to introduce flakiness to my tests.