From b94049f427b3f8ae52ba7be97675b4fc1f08f7b9 Mon Sep 17 00:00:00 2001 From: pon-james Date: Wed, 19 Oct 2022 10:25:58 +0100 Subject: [PATCH] feat(examples): add code from workshop examples Add example.js and example.test.js with a contrived example of handing a fetch like utility --- src/consumers.test.js | 2 +- src/examples.js | 44 +++++++++++++++++-------------------------- src/examples.test.js | 20 ++++++++++++++++++++ 3 files changed, 38 insertions(+), 28 deletions(-) create mode 100644 src/examples.test.js diff --git a/src/consumers.test.js b/src/consumers.test.js index 1f3f257..1bfd6b6 100644 --- a/src/consumers.test.js +++ b/src/consumers.test.js @@ -20,7 +20,7 @@ describe.each([ // ['implementationSix', implementationSix ], ])("%s", (_, fn) => { - test("", () => { + test.skip("", () => { const result = fn(); expect(result).toEqual(EXPECTED_RESULT); }); diff --git a/src/examples.js b/src/examples.js index e482923..2324618 100644 --- a/src/examples.js +++ b/src/examples.js @@ -1,30 +1,20 @@ -// Here are some examples from the field: +const { myPromise } = require("./producers"); - -// Ref: https://github.com/pondigitalsolutions/bs_frontend/blob/main/src/api/api.js#L57-L61 -/** - * A simple wrapper to 'unwrap' a response, streight to body. - * - * @private - * @param {response} requestObject A JSON type response - * @returns {Object} Returns the body of a response - */ - async function resultHandler(requestObject) { - return requestObject - .then((response) => response.body) - ; +async function getDataFromApi(ok = true) { + // handle first promise + const firstPromise = await myPromise; + // handle second promise + try { + const result = await myPromise; + if (!ok) { + return Promise.reject("Yikes, there was an error"); + } + return result; + } catch (error) { + // handle the error } +} -// Ref: https://github.com/pondigitalsolutions/bs_frontend/blob/c713bd4a77229d6db8a3eafda0d637901b75f591/src/api/api.js#L21-L28 -/** - * A function to fetch authentication token from the MSAL instance - * using the idToken - */ - async function getAccessToken() { - return msalInstance.acquireTokenSilent({ - ...loginRequest, - }) - .then((response) => { - return response.idToken; - }); - } +module.exports = { + getDataFromApi, +}; diff --git a/src/examples.test.js b/src/examples.test.js new file mode 100644 index 0000000..4516ec1 --- /dev/null +++ b/src/examples.test.js @@ -0,0 +1,20 @@ +const { getDataFromApi } = require("./examples"); + +describe("getDataFromApi", () => { + test("should return a promise", () => { + const result = getDataFromApi(); + expect(result).toBeInstanceOf(Promise); + }); + test("should return a value", async () => { + const result = await getDataFromApi(); + expect(result).toEqual({ status: "done" }); + }); + test("should reject if there is an error", async () => { + expect.assertions(1); + try { + const result = await getDataFromApi(false); + } catch (error) { + expect(error).toMatch("Yikes, there was an error"); + } + }); +});