2021-02-12 05:02:49 +07:00
|
|
|
import { JSDOM } from "jsdom"
|
2021-02-12 05:23:07 +07:00
|
|
|
// Note: we need to import logger from the root
|
|
|
|
// because this is the logger used in logError in ../src/common/util
|
|
|
|
import { logger } from "../node_modules/@coder/logger"
|
2021-02-12 05:02:49 +07:00
|
|
|
|
|
|
|
describe("register", () => {
|
2021-02-23 05:50:26 +07:00
|
|
|
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
|
|
|
|
|
|
|
|
let spy: jest.SpyInstance
|
|
|
|
let loggerSpy: jest.SpyInstance
|
|
|
|
const mockRegisterFn = jest.fn(() => console.log("Mock register fn called"))
|
|
|
|
|
|
|
|
beforeAll(() => {
|
|
|
|
Object.defineProperty(global.navigator, "serviceWorker", {
|
|
|
|
value: {
|
|
|
|
register: mockRegisterFn,
|
|
|
|
},
|
2021-02-12 05:23:07 +07:00
|
|
|
})
|
2021-02-23 05:50:26 +07:00
|
|
|
})
|
2021-02-12 06:51:48 +07:00
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
beforeEach(() => {
|
|
|
|
spy = jest.spyOn(global.navigator.serviceWorker, "register")
|
|
|
|
})
|
2021-02-12 06:51:48 +07:00
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
afterEach(() => {
|
|
|
|
jest.resetModules()
|
2021-02-12 06:51:48 +07:00
|
|
|
})
|
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
afterAll(() => {
|
|
|
|
jest.restoreAllMocks()
|
|
|
|
})
|
2021-02-12 06:51:48 +07:00
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
it("should register a ServiceWorker", () => {
|
|
|
|
spy = jest.spyOn(global.navigator.serviceWorker, "register")
|
|
|
|
// 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()
|
|
|
|
})
|
2021-02-12 06:51:48 +07:00
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
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)
|
2021-02-12 06:51:48 +07:00
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
mockRegisterFn.mockImplementation(() => {
|
|
|
|
throw error
|
2021-02-12 06:51:48 +07:00
|
|
|
})
|
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
// Load service worker like you would in the browser
|
|
|
|
require("../src/browser/register")
|
2021-02-12 06:51:48 +07:00
|
|
|
|
2021-02-23 05:50:26 +07:00
|
|
|
expect(spy).toHaveBeenCalled()
|
|
|
|
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}`)
|
2021-02-12 05:02:49 +07:00
|
|
|
})
|
|
|
|
})
|