diff --git a/src/ionic/index.ts b/src/ionic/index.ts index e9b2675..cba8270 100644 --- a/src/ionic/index.ts +++ b/src/ionic/index.ts @@ -115,11 +115,22 @@ export const showPopover = async (options: PopoverOptions) => { * Show a progress bar at the top of the page (nprogress). */ export const showProgress = () => { + nprogressCounts.start++; + nprogress.start(); - return nprogress; + return { + done: () => { + // the `done` count gets incremented before the comparison + if (nprogressCounts.start === ++nprogressCounts.done) { + nprogress.done(); + } + }, + }; }; +const nprogressCounts = { start: 0, done: 0 }; + /** * Show a progress bar while awaiting a promise. */ diff --git a/src/ionic/ionic.spec.ts b/src/ionic/ionic.spec.ts new file mode 100644 index 0000000..fe58b37 --- /dev/null +++ b/src/ionic/ionic.spec.ts @@ -0,0 +1,51 @@ +import nprogress from 'nprogress'; +import { showProgress } from '.'; + +jest.mock('nprogress', () => ({ + start: jest.fn(() => {}), + done: jest.fn(() => {}), +})); + +describe('Ionic Helpers', () => { + describe('showProgress()', () => { + beforeEach(jest.clearAllMocks); + + it('should call nprogress.start()', () => { + expect(nprogress.start).toBeCalledTimes(0); + expect(nprogress.done).toBeCalledTimes(0); + + const progress = showProgress(); + + expect(nprogress.start).toBeCalledTimes(1); + expect(nprogress.done).toBeCalledTimes(0); + + progress.done(); + + expect(nprogress.start).toBeCalledTimes(1); + expect(nprogress.done).toBeCalledTimes(1); + }); + + it('should not call nprogress.done() when another progress has started in the meantime', async () => { + const actionOne = new Promise((resolve) => { + const progress = showProgress(); + setTimeout(() => { + progress.done(); + resolve(); + }, 1000); + }); + + const actionTwo = new Promise((resolve) => { + const progress = showProgress(); + setTimeout(() => { + progress.done(); + resolve(); + }, 500); + }); + + await Promise.all([actionOne, actionTwo]); + + expect(nprogress.start).toBeCalledTimes(2); + expect(nprogress.done).toBeCalledTimes(1); + }); + }); +});