-
Notifications
You must be signed in to change notification settings - Fork 6k
feat(testing): add unit tests for register #2719
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
4f1f2c7
fix: clean up comment in util.test.ts
jsjoeio 28b440a
feat: add cssStub to jest
jsjoeio 72b05ca
refactor: create registerServiceWorker fn
jsjoeio 06aeca0
feat(testing): add register test
jsjoeio a9f88af
refactor: use logger in serviceworker
jsjoeio 44b9874
feat: test failure to register service worker
jsjoeio 21f577d
refactor: add handleRegisterServiceWorker fn
jsjoeio 38891de
feat(test): add test handleRegisterServiceWorker
jsjoeio 7ef630f
refactor(register): use logError instead of logger
jsjoeio a44a514
refactor: use same syntax as logger spy
jsjoeio 027e8e5
refactor: use LogModule from Asher in tests
jsjoeio 711abd8
refactor: move loggerModule into helpers
jsjoeio 1470ff2
refactor: dont use actual logger in helper
jsjoeio 1c737f1
refactor: hoist jest.mock in constants
jsjoeio cb4185b
refactor: use loggerModule in util
jsjoeio e6a324b
refactor: update mocking logger in register test
jsjoeio b232dcb
feat(register): add test when navigator undefined
jsjoeio 80a1800
feat: add test for catching errors in Emitter
jsjoeio 46226ea
chore(testing): add service-worker-mock
jsjoeio ee0973c
feat: add logs to serviceWorker
jsjoeio 6b56e65
feat(testing): add serviceWorker tests
jsjoeio 8c14799
refactor: add custom mock for serviceWorker test
jsjoeio File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,24 @@ | ||
import { getOptions, normalize } from "../common/util" | ||
|
||
const options = getOptions() | ||
import { getOptions, normalize, logError } from "../common/util" | ||
|
||
import "./pages/error.css" | ||
import "./pages/global.css" | ||
import "./pages/login.css" | ||
|
||
if ("serviceWorker" in navigator) { | ||
async function registerServiceWorker(): Promise<void> { | ||
const options = getOptions() | ||
const path = normalize(`${options.csStaticBase}/dist/serviceWorker.js`) | ||
navigator.serviceWorker | ||
.register(path, { | ||
try { | ||
await navigator.serviceWorker.register(path, { | ||
scope: (options.base ?? "") + "/", | ||
}) | ||
.then(() => { | ||
console.log("[Service Worker] registered") | ||
}) | ||
console.log("[Service Worker] registered") | ||
} catch (error) { | ||
logError(`[Service Worker] registration`, error) | ||
} | ||
} | ||
|
||
if (typeof navigator !== "undefined" && "serviceWorker" in navigator) { | ||
registerServiceWorker() | ||
} else { | ||
console.error(`[Service Worker] navigator is undefined`) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
// Note: this is needed for the register.test.ts | ||
// This is because inside src/browser/register.ts | ||
// we import CSS files, which Jest can't handle unless we tell it how to | ||
// See: https://stackoverflow.com/a/39434579/3015595 | ||
module.exports = {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
import { JSDOM } from "jsdom" | ||
import { loggerModule } from "./helpers" | ||
|
||
describe("register", () => { | ||
describe("when navigator and serviceWorker are defined", () => { | ||
const mockRegisterFn = jest.fn() | ||
|
||
beforeAll(() => { | ||
const { window } = new JSDOM() | ||
global.window = (window as unknown) as Window & typeof globalThis | ||
global.document = window.document | ||
global.navigator = window.navigator | ||
global.location = window.location | ||
|
||
Object.defineProperty(global.navigator, "serviceWorker", { | ||
value: { | ||
register: mockRegisterFn, | ||
}, | ||
}) | ||
}) | ||
|
||
beforeEach(() => { | ||
jest.mock("@coder/logger", () => loggerModule) | ||
}) | ||
jsjoeio marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
afterEach(() => { | ||
mockRegisterFn.mockClear() | ||
jest.resetModules() | ||
}) | ||
|
||
afterAll(() => { | ||
jest.restoreAllMocks() | ||
|
||
// We don't want these to stay around because it can affect other tests | ||
global.window = (undefined as unknown) as Window & typeof globalThis | ||
global.document = (undefined as unknown) as Document & typeof globalThis | ||
global.navigator = (undefined as unknown) as Navigator & typeof globalThis | ||
global.location = (undefined as unknown) as Location & typeof globalThis | ||
}) | ||
|
||
it("should register a ServiceWorker", () => { | ||
// Load service worker like you would in the browser | ||
require("../src/browser/register") | ||
expect(mockRegisterFn).toHaveBeenCalled() | ||
expect(mockRegisterFn).toHaveBeenCalledTimes(1) | ||
}) | ||
|
||
it("should log an error if something doesn't work", () => { | ||
const message = "Can't find browser" | ||
const error = new Error(message) | ||
|
||
mockRegisterFn.mockImplementation(() => { | ||
throw error | ||
}) | ||
|
||
// Load service worker like you would in the browser | ||
require("../src/browser/register") | ||
|
||
expect(mockRegisterFn).toHaveBeenCalled() | ||
expect(loggerModule.logger.error).toHaveBeenCalled() | ||
expect(loggerModule.logger.error).toHaveBeenCalledTimes(1) | ||
expect(loggerModule.logger.error).toHaveBeenCalledWith( | ||
`[Service Worker] registration: ${error.message} ${error.stack}`, | ||
) | ||
}) | ||
}) | ||
|
||
describe("when navigator and serviceWorker are NOT defined", () => { | ||
let spy: jest.SpyInstance | ||
|
||
beforeEach(() => { | ||
spy = jest.spyOn(console, "error") | ||
}) | ||
|
||
afterAll(() => { | ||
jest.restoreAllMocks() | ||
}) | ||
|
||
it("should log an error to the console", () => { | ||
// Load service worker like you would in the browser | ||
require("../src/browser/register") | ||
expect(spy).toHaveBeenCalled() | ||
expect(spy).toHaveBeenCalledTimes(1) | ||
expect(spy).toHaveBeenCalledWith("[Service Worker] navigator is undefined") | ||
}) | ||
}) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
interface MockEvent { | ||
claim: jest.Mock<any, any> | ||
waitUntil?: jest.Mock<any, any> | ||
} | ||
|
||
interface Listener { | ||
event: string | ||
cb: (event?: MockEvent) => void | ||
} | ||
|
||
describe("serviceWorker", () => { | ||
let listeners: Listener[] = [] | ||
let spy: jest.SpyInstance | ||
let claimSpy: jest.Mock<any, any> | ||
let waitUntilSpy: jest.Mock<any, any> | ||
|
||
function emit(event: string) { | ||
listeners | ||
.filter((listener) => listener.event === event) | ||
.forEach((listener) => { | ||
switch (event) { | ||
case "activate": | ||
listener.cb({ | ||
claim: jest.fn(), | ||
waitUntil: jest.fn(() => waitUntilSpy()), | ||
}) | ||
break | ||
default: | ||
listener.cb() | ||
} | ||
}) | ||
} | ||
|
||
beforeEach(() => { | ||
claimSpy = jest.fn() | ||
spy = jest.spyOn(console, "log") | ||
waitUntilSpy = jest.fn() | ||
|
||
Object.assign(global, { | ||
self: global, | ||
addEventListener: (event: string, cb: () => void) => { | ||
listeners.push({ event, cb }) | ||
}, | ||
clients: { | ||
claim: claimSpy.mockResolvedValue("claimed"), | ||
}, | ||
}) | ||
}) | ||
|
||
afterEach(() => { | ||
jest.restoreAllMocks() | ||
jest.resetModules() | ||
spy.mockClear() | ||
claimSpy.mockClear() | ||
|
||
// Clear all the listeners | ||
listeners = [] | ||
}) | ||
|
||
it("should add 3 listeners: install, activate and fetch", () => { | ||
require("../src/browser/serviceWorker.ts") | ||
const listenerEventNames = listeners.map((listener) => listener.event) | ||
|
||
expect(listeners).toHaveLength(3) | ||
expect(listenerEventNames).toContain("install") | ||
expect(listenerEventNames).toContain("activate") | ||
expect(listenerEventNames).toContain("fetch") | ||
}) | ||
|
||
it("should call the proper callbacks for 'install'", async () => { | ||
require("../src/browser/serviceWorker.ts") | ||
emit("install") | ||
expect(spy).toHaveBeenCalledWith("[Service Worker] installed") | ||
expect(spy).toHaveBeenCalledTimes(1) | ||
}) | ||
|
||
it("should do nothing when 'fetch' is called", async () => { | ||
require("../src/browser/serviceWorker.ts") | ||
emit("fetch") | ||
expect(spy).not.toHaveBeenCalled() | ||
}) | ||
|
||
it("should call the proper callbacks for 'activate'", async () => { | ||
require("../src/browser/serviceWorker.ts") | ||
emit("activate") | ||
|
||
// Activate serviceWorker | ||
expect(spy).toHaveBeenCalledWith("[Service Worker] activated") | ||
expect(waitUntilSpy).toHaveBeenCalled() | ||
expect(claimSpy).toHaveBeenCalled() | ||
}) | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.