I want to test myFunction(), which is expected to turn var appState from "old state" to "new state". However, myFunction() invokes n functions fetcher() which contain the async function fetch - similar to the psudocode below.
// Application code
myFunction() = function {
for (var i = 0, len = myarray.length; i < len; i++) {
fetcher()
}
}
fetcher = function(){
fetch(url) // Is asynchronous
.then(response => response.json())
.then(data => {
if(data == 'abc'){ appState = "new state" }
}
}
// Test
myFunction()
setTimeout(() => {
assert.equal(appState, "New State")
}, 10);
This timeout works fine and the test passes, but it feels like a code smell. Is there a more correct way to wait for the async functions generated by myFunction() to complete before testing the new state?