@mblaney/holster-browser 1.1.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+ import {describe, it, expect, beforeEach, vi} from "vitest"
2
+ import {render, screen, act} from "@testing-library/react"
3
+ import userEvent from "@testing-library/user-event"
4
+ import Signup from "../Signup.jsx"
5
+
6
+ function createMockUser({createErr = null, authErr = null, is = null} = {}) {
7
+ const user = {
8
+ is,
9
+ SEA: {sign: vi.fn(() => Promise.resolve("mock-signed"))},
10
+ create: vi.fn((username, password, cb) => cb(createErr)),
11
+ auth: vi.fn((username, password, cb) => {
12
+ if (!authErr) user.is = {pub: "mock-pub", epub: "mock-epub"}
13
+ cb(authErr)
14
+ }),
15
+ delete: vi.fn((username, password, cb) => cb && cb(null)),
16
+ }
17
+ return user
18
+ }
19
+
20
+ function mockFetchResponse(ok, text) {
21
+ return Promise.resolve({ok, text: () => Promise.resolve(text)})
22
+ }
23
+
24
+ async function fillAndSubmit({username, email}) {
25
+ if (username !== undefined) {
26
+ await userEvent.type(screen.getByLabelText("Username"), username)
27
+ }
28
+ if (email !== undefined) {
29
+ await userEvent.type(screen.getByLabelText("Email"), email)
30
+ }
31
+ await userEvent.click(screen.getByRole("button", {name: "Submit"}))
32
+ }
33
+
34
+ describe("Signup Component", () => {
35
+ beforeEach(() => {
36
+ vi.clearAllMocks()
37
+ vi.stubGlobal("fetch", vi.fn())
38
+ delete window.location
39
+ window.location = {href: ""}
40
+ })
41
+
42
+ it("renders the signup form", () => {
43
+ const user = createMockUser()
44
+ render(<Signup user={user} />)
45
+ expect(screen.getByText("Sign up")).toBeTruthy()
46
+ expect(screen.getByLabelText("Username")).toBeTruthy()
47
+ expect(screen.getByLabelText("Email")).toBeTruthy()
48
+ })
49
+
50
+ it("shows already logged in and disables submit when a user is present", () => {
51
+ const user = createMockUser({is: {pub: "existing-pub"}})
52
+ render(<Signup user={user} />)
53
+ expect(screen.getByText("Already logged in")).toBeTruthy()
54
+ expect(screen.getByRole("button", {name: "Submit"})).toBeDisabled()
55
+ })
56
+
57
+ it("requires a username", async () => {
58
+ const user = createMockUser()
59
+ render(<Signup user={user} />)
60
+ await act(async () => {
61
+ await fillAndSubmit({email: "alice@test.com"})
62
+ })
63
+ expect(screen.getByText("Please choose a username")).toBeTruthy()
64
+ expect(user.create).not.toHaveBeenCalled()
65
+ })
66
+
67
+ it("rejects a username with invalid characters", async () => {
68
+ const user = createMockUser()
69
+ render(<Signup user={user} />)
70
+ await act(async () => {
71
+ await fillAndSubmit({username: "alice!", email: "alice@test.com"})
72
+ })
73
+ expect(
74
+ screen.getByText(
75
+ "Username must contain only numbers, letters and underscore",
76
+ ),
77
+ ).toBeTruthy()
78
+ expect(user.create).not.toHaveBeenCalled()
79
+ })
80
+
81
+ it("requires an email", async () => {
82
+ const user = createMockUser()
83
+ render(<Signup user={user} />)
84
+ await act(async () => {
85
+ await fillAndSubmit({username: "alice"})
86
+ })
87
+ expect(screen.getByText("Please provide your email")).toBeTruthy()
88
+ expect(user.create).not.toHaveBeenCalled()
89
+ })
90
+
91
+ it("submits the typed password", async () => {
92
+ const user = createMockUser()
93
+ fetch.mockReturnValue(mockFetchResponse(true, ""))
94
+ render(<Signup user={user} />)
95
+
96
+ await act(async () => {
97
+ await userEvent.type(screen.getByLabelText("Username"), "alice")
98
+ await userEvent.type(screen.getByLabelText("Password"), "hunter2")
99
+ await userEvent.type(screen.getByLabelText("Email"), "alice@test.com")
100
+ await userEvent.click(screen.getByRole("button", {name: "Submit"}))
101
+ })
102
+
103
+ expect(user.create).toHaveBeenCalledWith(
104
+ "alice",
105
+ "hunter2",
106
+ expect.any(Function),
107
+ )
108
+ })
109
+
110
+ it("creates the account, posts to /signup, and redirects on success", async () => {
111
+ const user = createMockUser()
112
+ fetch.mockReturnValue(mockFetchResponse(true, ""))
113
+ render(<Signup user={user} />)
114
+
115
+ await act(async () => {
116
+ await fillAndSubmit({username: "alice", email: "alice@test.com"})
117
+ })
118
+
119
+ expect(user.create).toHaveBeenCalledWith("alice", "", expect.any(Function))
120
+ expect(user.auth).toHaveBeenCalledWith("alice", "", expect.any(Function))
121
+ expect(user.SEA.sign).toHaveBeenCalledWith(
122
+ {
123
+ username: "alice",
124
+ email: "alice@test.com",
125
+ timestamp: expect.any(Number),
126
+ },
127
+ {pub: "mock-pub", epub: "mock-epub"},
128
+ )
129
+ expect(fetch).toHaveBeenCalledWith(
130
+ expect.stringContaining("/signup"),
131
+ expect.objectContaining({
132
+ method: "POST",
133
+ body: JSON.stringify({
134
+ pub: "mock-pub",
135
+ epub: "mock-epub",
136
+ signed: "mock-signed",
137
+ }),
138
+ }),
139
+ )
140
+ expect(screen.getByText("Account created")).toBeTruthy()
141
+ expect(window.location).toBe("/login")
142
+ })
143
+
144
+ it("deletes the local account and shows the error on failure", async () => {
145
+ const user = createMockUser()
146
+ fetch.mockReturnValue(
147
+ mockFetchResponse(
148
+ false,
149
+ "Signup is not available, please try again in a few minutes",
150
+ ),
151
+ )
152
+ render(<Signup user={user} />)
153
+
154
+ await act(async () => {
155
+ await fillAndSubmit({username: "alice", email: "alice@test.com"})
156
+ })
157
+
158
+ expect(user.delete).toHaveBeenCalledWith("alice", "", expect.any(Function))
159
+ expect(
160
+ screen.getByText(
161
+ "Signup is not available, please try again in a few minutes",
162
+ ),
163
+ ).toBeTruthy()
164
+ expect(window.location).toEqual({href: ""})
165
+ })
166
+
167
+ it("shows the error and stops when user.create fails", async () => {
168
+ const user = createMockUser({createErr: "username already taken"})
169
+ render(<Signup user={user} />)
170
+
171
+ await act(async () => {
172
+ await fillAndSubmit({username: "alice", email: "alice@test.com"})
173
+ })
174
+
175
+ expect(screen.getByText("username already taken")).toBeTruthy()
176
+ expect(user.auth).not.toHaveBeenCalled()
177
+ expect(fetch).not.toHaveBeenCalled()
178
+ })
179
+
180
+ it("shows the error and stops when user.auth fails", async () => {
181
+ const user = createMockUser({authErr: "wrong password"})
182
+ render(<Signup user={user} />)
183
+
184
+ await act(async () => {
185
+ await fillAndSubmit({username: "alice", email: "alice@test.com"})
186
+ })
187
+
188
+ expect(screen.getByText("wrong password")).toBeTruthy()
189
+ expect(fetch).not.toHaveBeenCalled()
190
+ })
191
+ })
package/src/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export {default as EditCache} from "./components/EditCache.jsx"
2
2
  export {default as RequestCode} from "./components/RequestCode.jsx"
3
+ export {default as Signup} from "./components/Signup.jsx"
3
4
  export {default as LoginCodes} from "./components/LoginCodes.jsx"
4
5
  export {default as Login} from "./components/Login.jsx"
5
6
  export {default as Register} from "./components/Register.jsx"
@@ -8,5 +9,4 @@ export {default as SearchAppBar} from "./components/SearchAppBar.jsx"
8
9
  export {default as Settings} from "./components/Settings.jsx"
9
10
  export {default as UpdatePassword} from "./components/UpdatePassword.jsx"
10
11
  export {default as ValidateEmail} from "./components/ValidateEmail.jsx"
11
- export {register as registerServiceWorker} from "./utils/serviceWorkerRegistration.js"
12
12
  export {useAccountSync} from "./hooks/useAccountSync.js"
@@ -1,88 +0,0 @@
1
- const isLocalhost = Boolean(
2
- window.location.hostname === "localhost" ||
3
- window.location.hostname === "[::1]" ||
4
- window.location.hostname.match(
5
- /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/,
6
- ),
7
- )
8
-
9
- export function register(config) {
10
- if (import.meta.env.PROD && "serviceWorker" in navigator) {
11
- window.addEventListener("load", () => {
12
- const swUrl = `${import.meta.env.BASE_URL}service-worker.js`
13
-
14
- if (isLocalhost) {
15
- checkValidServiceWorker(swUrl, config)
16
- } else {
17
- registerValidSW(swUrl, config)
18
- }
19
- })
20
- }
21
- }
22
-
23
- function registerValidSW(swUrl, config) {
24
- navigator.serviceWorker
25
- .register(swUrl)
26
- .then(registration => {
27
- registration.onupdatefound = () => {
28
- const installingWorker = registration.installing
29
- if (installingWorker == null) {
30
- return
31
- }
32
- installingWorker.onstatechange = () => {
33
- if (installingWorker.state === "installed") {
34
- if (navigator.serviceWorker.controller) {
35
- if (config && config.onUpdate) {
36
- config.onUpdate(registration)
37
- }
38
- } else {
39
- if (config && config.onSuccess) {
40
- config.onSuccess(registration)
41
- }
42
- }
43
- }
44
- }
45
- }
46
- })
47
- .catch(error => {
48
- console.error("Error during service worker registration:", error)
49
- })
50
- }
51
-
52
- function checkValidServiceWorker(swUrl, config) {
53
- fetch(swUrl, {
54
- headers: {"Service-Worker": "script"},
55
- })
56
- .then(response => {
57
- const contentType = response.headers.get("content-type")
58
- if (
59
- response.status === 404 ||
60
- (contentType != null && contentType.indexOf("javascript") === -1)
61
- ) {
62
- navigator.serviceWorker.ready.then(registration => {
63
- registration.unregister().then(() => {
64
- window.location.reload()
65
- })
66
- })
67
- } else {
68
- registerValidSW(swUrl, config)
69
- }
70
- })
71
- .catch(() => {
72
- console.log(
73
- "No internet connection found. App is running in offline mode.",
74
- )
75
- })
76
- }
77
-
78
- export function unregister() {
79
- if ("serviceWorker" in navigator) {
80
- navigator.serviceWorker.ready
81
- .then(registration => {
82
- registration.unregister()
83
- })
84
- .catch(error => {
85
- console.error(error.message)
86
- })
87
- }
88
- }