How to Handle Time and Date
Learn how to use the clock to mock the passage of time.
We'll cover the following...
We can use Jasmine’s clock
to mock the passage of time. For example, if we have a function that runs after a timeout, we would have to wait for the function to finish before we can make an expectation about the result. We can use the Jasmine clock
fake to fast-forward the system time to get the function to run. In the example below, we have a method that fetches data after three seconds.
const book = { title: 'Don Quixote', author: 'Miguel de Cervantes', year: '1605' }; let bookRepository = { index: () => { // Call an external API return [book, book, book]; }, } class BookDetailPage { init = () => { setTimeout(() => { this.data = bookRepository.index(); }, 3000); } } describe('Book detail tests', () => { beforeEach(() => { jasmine.clock().install(); }); it('Loads data from the API', () => { let page = new BookDetailPage(); page.init(); expect(page.data).toBeUndefined(); jasmine.clock().tick(3001); expect(page.data[0]).toEqual({ title: 'Don Quixote', author: 'Miguel de Cervantes', year: '1605' }); }); afterEach(() => { jasmine.clock().uninstall(); }); });
Go ahead and experiment with the example above. What happens if we remove the code on line 33?
jasmine.clock().tick(3001);
The code snippet above shows the tick
method to advance the clock by 3001
milliseconds.
If we remove this line, we don’t need to fast-forward the mock clock. As a result, the setTimeout
callback, defined on line 16, does not run, and our test fails. ...