From 73973edab9aaa81312ba80a68bfe34bf5abcecd9 Mon Sep 17 00:00:00 2001 From: Ruben Beltran del Rio Date: Sun, 2 May 2021 00:23:16 +0200 Subject: Add pact test for forums store --- src/utils/resolve_after.js | 25 +++++++++++++++++++++++ src/utils/resolve_after.test.js | 45 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 src/utils/resolve_after.js create mode 100644 src/utils/resolve_after.test.js (limited to 'src/utils') diff --git a/src/utils/resolve_after.js b/src/utils/resolve_after.js new file mode 100644 index 0000000..0884401 --- /dev/null +++ b/src/utils/resolve_after.js @@ -0,0 +1,25 @@ +export const resolveAfter = function (timesUntilResolve) { + + let counter = null; + let currentValue = 0; + + if (typeof timesUntilResolve !== 'number' || timesUntilResolve <= 0) { + throw new Error('Resolve after requires a positive integer'); + } + + const promise = new Promise((resolvePromise) => { + + counter = () => { + + if (++currentValue === timesUntilResolve) { + resolvePromise(); + } + }; + }); + + return { + counter, + promise + }; + +}; diff --git a/src/utils/resolve_after.test.js b/src/utils/resolve_after.test.js new file mode 100644 index 0000000..f7fc753 --- /dev/null +++ b/src/utils/resolve_after.test.js @@ -0,0 +1,45 @@ +import { resolveAfter } from './resolve_after'; + +describe('Resolve After', () => { + + test('it should throw if given 0', () => { + + expect(() => { + + resolveAfter(0); + }).toThrow(); + }); + + test('it should throw if given a negative number', () => { + + expect(() => { + + resolveAfter(-1); + }).toThrow(); + }); + + test('it should throw if given a negative number', () => { + + expect(() => { + + resolveAfter('lol'); + }).toThrow(); + }); + + test('it should resolve after the specified number of times', () => { + + expect(() => { + + const { counter, resolveAfterThree } = resolveAfter(3); + let resolved = false; + + resolveAfterThree.then(() => (resolved = true)); + counter(); + expect(resolved).toBe(false); + counter(); + expect(resolved).toBe(false); + counter(); + expect(resolved).toBe(true); + }).toThrow(); + }); +}); -- cgit