I use jasmine runs and wait to test asynchronous operations. Everything works fine but I\'m not quite sure what goes on behind the scenes.
The jasmine documentation
waitsFor
does block until the conditions it's waiting for are met or it times out.
From the jasmine docs: "waitsFor() provides a better interface for pausing your spec until some other work has completed. Jasmine will wait until the provided function returns true before continuing with the next block.".
The linked docs also have a slightly clearer example or waitsFor
.
EDIT: Ah I see what you mean now. waitsFor
won't block JS that isn't wrapped in runs
, waitsFor
, ect.
What jasmine is doing is taking the function passed to it via runs
or waitsFor
and if jasmine is not currently waiting, it executes the function immediately. If it is waiting, it doesn't call it until it's finished waiting.
That doesn't stop the console.log
as it's been passed to jasmine so jasmine can't prevent it from being executed straight away.
From the site: http://www.htmlgoodies.com/beyond/javascript/test-asynchronous-methods-using-the-jasmine-runs-and-waitfor-methods.html#fbid=mzNDUVfhFXg
Jasmine will call the runs() and waitsFor() methods in the order you passed them. As soon as the JS parser gets to a waitsFor() method it will poll it until it returns true and only then will it continue onto the next runs() method.
Essentially, the runs() and waitsFor() functions stuff an array with their provided functions. The array is then processed by jamine wherein the functions are invoked sequentially. Those functions registered by runs() are expected to perform actual work while those registered by waitsFor() are expected to be 'latch' functions and will be polled (invoked) every 10ms until they return true or the optional registered timeout period expires. If the timeout period expires an error is reported using the optional registered error message; otherwise, the process continues with the next function in the array. Presumably, expects within the runs() can also trigger a failure report (and perhaps even in the latch functions themselves).
The documentation is particularly obtuse on these asynchronous features.
The solution is in the documentation:
Multiple runs() blocks in a spec will run serially. (Jasmine Documentation)