Skip to content

Instantly share code, notes, and snippets.

@georgiee
Last active December 8, 2018 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georgiee/fa2e9eec676cc0d6e63e66229595c51c to your computer and use it in GitHub Desktop.
Save georgiee/fa2e9eec676cc0d6e63e66229595c51c to your computer and use it in GitHub Desktop.
One Angular Test can explain asynchronicity in Angular
it('setTimeout & tick & flushMicrotasks', fakeAsync(() => {
let state = [];
// add to the micro task queue — will be the first thing executed after this script block is done
Promise.resolve().then(function() {
state.push('promise result');
});
// add to the task queue — will be executed after this task and when the micro task queue is emptied
setTimeout(() => { state.push('timeout called'); });
// add to the task queue after 2 seconds
setTimeout(() => { state.push('timeout called after 2s'); }, 2000);
expect(state).toEqual([]);
flushMicrotasks();
expect(state).toEqual(['promise result']);
tick();
expect(state).toEqual(['promise result', 'timeout called']);
tick(2000);
expect(state).toEqual(['promise result', 'timeout called', 'timeout called after 2s']);
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment