Archived
1
0

refactor: use same syntax as logger spy

This commit is contained in:
Joe Previte 2021-02-22 15:50:26 -07:00
parent 7ef630f7a4
commit a44a51462c
No known key found for this signature in database
GPG Key ID: 2C91590C6B742C24
3 changed files with 58 additions and 138 deletions

View File

@ -1,10 +1,12 @@
import { getOptions, Options, normalize, logError } from "../common/util" import { getOptions, normalize, logError } from "../common/util"
import "./pages/error.css" import "./pages/error.css"
import "./pages/global.css" import "./pages/global.css"
import "./pages/login.css" import "./pages/login.css"
export async function registerServiceWorker(navigator: Navigator, path: string, options: Options): Promise<void> { async function registerServiceWorker(): Promise<void> {
const options = getOptions()
const path = normalize(`${options.csStaticBase}/dist/serviceWorker.js`)
try { try {
await navigator.serviceWorker.register(path, { await navigator.serviceWorker.register(path, {
scope: (options.base ?? "") + "/", scope: (options.base ?? "") + "/",
@ -15,23 +17,8 @@ export async function registerServiceWorker(navigator: Navigator, path: string,
} }
} }
interface HandleServiceWorkerRegistration { if (typeof navigator !== "undefined" && "serviceWorker" in navigator) {
getOptions: () => Options registerServiceWorker()
normalize: (url: string, keepTrailing?: boolean) => string } else {
registerServiceWorker: (navigator: Navigator, path: string, options: Options) => Promise<void> console.error(`[Service Worker] navigator is undefined`)
} }
export function handleServiceWorkerRegistration({
getOptions,
normalize,
registerServiceWorker,
}: HandleServiceWorkerRegistration): void {
if (typeof navigator !== "undefined" && "serviceWorker" in navigator) {
const options = getOptions()
const path = normalize(`${options.csStaticBase}/dist/serviceWorker.js`)
registerServiceWorker(navigator, path, options)
}
}
// Written this way so that it's easier to test
handleServiceWorkerRegistration({ getOptions, normalize, registerServiceWorker })

View File

@ -114,9 +114,12 @@ export const getFirstString = (value: string | string[] | object | undefined): s
} }
export function logError(prefix: string, err: any): void { export function logError(prefix: string, err: any): void {
console.log("hey joe log error was called")
if (err instanceof Error) { if (err instanceof Error) {
console.log("it was an instance of error")
logger.error(`${prefix}: ${err.message} ${err.stack}`) logger.error(`${prefix}: ${err.message} ${err.stack}`)
} else { } else {
console.log("not an isntance errro")
logger.error(`${prefix}: ${err}`) logger.error(`${prefix}: ${err}`)
} }
} }

View File

@ -2,135 +2,65 @@ import { JSDOM } from "jsdom"
// Note: we need to import logger from the root // Note: we need to import logger from the root
// because this is the logger used in logError in ../src/common/util // because this is the logger used in logError in ../src/common/util
import { logger } from "../node_modules/@coder/logger" import { logger } from "../node_modules/@coder/logger"
import { registerServiceWorker, handleServiceWorkerRegistration } from "../src/browser/register"
import { Options } from "../src/common/util"
const { window } = new JSDOM()
global.window = (window as unknown) as Window & typeof globalThis
global.document = window.document
global.navigator = window.navigator
describe("register", () => { describe("register", () => {
describe("registerServiceWorker", () => { const { window } = new JSDOM()
let spy: jest.MockedFunction<( global.window = (window as unknown) as Window & typeof globalThis
scriptURL: string, global.document = window.document
options?: RegistrationOptions | undefined, global.navigator = window.navigator
) => Promise<ServiceWorkerRegistration>> global.location = window.location
let loggerSpy: jest.SpyInstance
beforeAll(() => { let spy: jest.SpyInstance
Object.defineProperty(global.navigator, "serviceWorker", { let loggerSpy: jest.SpyInstance
value: { const mockRegisterFn = jest.fn(() => console.log("Mock register fn called"))
register: () => {
return "hello"
},
},
})
})
beforeEach(() => { beforeAll(() => {
loggerSpy = jest.spyOn(logger, "error") Object.defineProperty(global.navigator, "serviceWorker", {
spy = jest.fn() value: {
global.navigator.serviceWorker.register = spy register: mockRegisterFn,
}) },
afterEach(() => {
jest.resetAllMocks()
})
afterAll(() => {
jest.restoreAllMocks()
})
it("should register a ServiceWorker", () => {
global.navigator.serviceWorker.register = spy
const path = "/hello"
const mockOptions = {
base: "",
csStaticBase: "",
logLevel: 0,
}
registerServiceWorker(navigator, path, mockOptions)
// expect spy to have been called
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledTimes(1)
})
it("should log an error if something doesn't work", () => {
const message = "Can't find browser"
const error = new Error(message)
const path = "/hello"
const mockOptions = {
base: "",
csStaticBase: "",
logLevel: 0,
}
global.navigator.serviceWorker.register = () => {
throw error
}
registerServiceWorker(navigator, path, mockOptions)
expect(loggerSpy).toHaveBeenCalled()
expect(loggerSpy).toHaveBeenCalledTimes(1)
// Because we use logError, it will log the prefix along with the error message
expect(loggerSpy).toHaveBeenCalledWith(`[Service Worker] registration: ${error.message} ${error.stack}`)
})
it("should work when base is undefined", () => {
const path = "/hello"
// We want to test some code that checks if options.base is undefined
// so we leave it off mockOptions
// but assert it as Options so TS is happy
const mockOptions = {
csStaticBase: "",
logLevel: 0,
} as Options
registerServiceWorker(navigator, path, mockOptions)
// expect spy to have been called
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledTimes(1)
}) })
}) })
describe("handleServiceWorkerRegistration", () => { beforeEach(() => {
let getOptionsMock: jest.MockedFunction<() => { spy = jest.spyOn(global.navigator.serviceWorker, "register")
base: string })
csStaticBase: string
logLevel: number
}>
let normalizeMock: jest.MockedFunction<(v: string) => string>
let registerServiceWorkerMock: jest.MockedFunction<(
navigator: Navigator,
path: string,
mockOptions: Options,
) => Promise<void>>
beforeEach(() => { afterEach(() => {
getOptionsMock = jest.fn(() => ({ jest.resetModules()
base: "", })
csStaticBase: "",
logLevel: 0,
}))
normalizeMock = jest.fn((url: string) => "qux///") afterAll(() => {
jest.restoreAllMocks()
})
registerServiceWorkerMock = jest it("should register a ServiceWorker", () => {
.fn() spy = jest.spyOn(global.navigator.serviceWorker, "register")
.mockImplementation((navigator: Navigator, path: string, mockOptions: Options) => Promise.resolve()) // Load service worker like you would in the browser
require("../src/browser/register")
// Load service worker like you would in the browser
// expect spy to have been called
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledTimes(1)
spy.mockClear()
})
it("should log an error if something doesn't work", () => {
loggerSpy = jest.spyOn(logger, "error")
const message = "Can't find browser"
const error = new Error(message)
mockRegisterFn.mockImplementation(() => {
throw error
}) })
it("should work when called", () => {
handleServiceWorkerRegistration({
getOptions: getOptionsMock,
normalize: normalizeMock,
registerServiceWorker: registerServiceWorkerMock,
})
const mocks = [getOptionsMock, normalizeMock, registerServiceWorkerMock] // Load service worker like you would in the browser
require("../src/browser/register")
mocks.forEach((mock) => { expect(spy).toHaveBeenCalled()
expect(mock).toHaveBeenCalled() expect(loggerSpy).toHaveBeenCalled()
expect(mock).toHaveBeenCalledTimes(1) // expect(loggerSpy).toHaveBeenCalledTimes(1)
}) // Because we use logError, it will log the prefix along with the error message
}) // expect(loggerSpy).toHaveBeenCalledWith(`[Service Worker] registration: ${error.message} ${error.stack}`)
}) })
}) })