diff --git a/chapter05/src/validate_user.js b/chapter05/src/validate_user.js new file mode 100644 index 0000000..a061a05 --- /dev/null +++ b/chapter05/src/validate_user.js @@ -0,0 +1,25 @@ +/* @flow */ +"use strict"; + +/* + In real life, validateUser could check a database, + look into an Active Directory, call another service, + etc. -- but for this demo, let's keep it quite + simple and only accept a single hardcoded user. +*/ + +const validateUser = ( + userName: string, + password: string, + callback: (?string, ?string) => void +) => { + if (!userName || !password) { + callback("Missing user/password", null); + } else if (userName === "fkereki" && password === "modernjsbook") { + callback(null, "fkereki"); // OK, send userName back + } else { + callback("Not valid user", null); + } +}; + +module.exports = validateUser; diff --git a/chapter05/src/validate_user.test.js b/chapter05/src/validate_user.test.js new file mode 100644 index 0000000..226f0e5 --- /dev/null +++ b/chapter05/src/validate_user.test.js @@ -0,0 +1,25 @@ +/* @flow */ +"use strict"; + +const validateUser = require("./validate_user"); + +describe("validateUser", () => { + it("should reject a call with empty user", () => { + const cb = jest.fn(); + validateUser("", "somepass", cb); + expect(cb).toHaveBeenCalled(); + expect(cb).toHaveBeenCalledWith("Missing user/password", null); + }); + + it("should reject a wrong password", () => { + const cb = jest.fn(); + validateUser("fkereki", "wrongpassword", cb); + expect(cb).toHaveBeenCalledWith("Not valid user", null); + }); + + it("should accept a correct password", () => { + const cb = jest.fn(); + validateUser("fkereki", "modernjsbook", cb); + expect(cb).toHaveBeenCalledWith(null, "fkereki"); + }); +});