From 1afc47e7fe23168441c46e6ce60cc6d8c76dd79d Mon Sep 17 00:00:00 2001 From: pseidemann Date: Wed, 23 Aug 2023 11:23:46 +0200 Subject: [PATCH] useAuth should not throw --- src/useAuth.ts | 4 ++-- test/useAuth.test.tsx | 14 +++----------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/src/useAuth.ts b/src/useAuth.ts index 9bc82732..e3c9e40d 100644 --- a/src/useAuth.ts +++ b/src/useAuth.ts @@ -9,8 +9,8 @@ export const useAuth = (): AuthContextProps => { const context = React.useContext(AuthContext); if (!context) { - throw new Error("AuthProvider context is undefined, please verify you are calling useAuth() as child of a component."); + console.warn("AuthProvider context is undefined, please verify you are calling useAuth() as child of a component."); } - return context; + return context as AuthContextProps; }; diff --git a/test/useAuth.test.tsx b/test/useAuth.test.tsx index 46283b28..36c0237d 100644 --- a/test/useAuth.test.tsx +++ b/test/useAuth.test.tsx @@ -18,16 +18,8 @@ describe("useAuth", () => { await waitFor(() => expect(result.current).toBeDefined()); }); - it("should throw with no provider", async () => { - // act - try { - renderHook(() => useAuth()); - } catch (err) { - //assert - expect(err).toBeInstanceOf(Error); - expect((err as Error).message).toContain( - "AuthProvider context is undefined, please verify you are calling useAuth() as child of a component.", - ); - } + it("should return undefined with no provider", async () => { + const { result } = renderHook(() => useAuth()); + expect(result.current).toBeUndefined(); }); });