code-server/test/unit/serviceWorker.test.ts

93 lines
2.4 KiB
TypeScript
Raw Normal View History

interface MockEvent {
claim: jest.Mock<any, any>
waitUntil?: jest.Mock<any, any>
}
interface Listener {
event: string
cb: (event?: MockEvent) => void
}
2021-02-18 22:35:41 +01:00
describe("serviceWorker", () => {
let listeners: Listener[] = []
2021-02-18 22:35:41 +01:00
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()
}
})
}
2021-02-18 22:35:41 +01:00
beforeEach(() => {
claimSpy = jest.fn()
2021-02-18 22:35:41 +01:00
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"),
},
})
2021-02-18 22:35:41 +01:00
})
afterEach(() => {
jest.restoreAllMocks()
jest.resetModules()
spy.mockClear()
claimSpy.mockClear()
// Clear all the listeners
listeners = []
2021-02-18 22:35:41 +01:00
})
it("should add 3 listeners: install, activate and fetch", () => {
2021-03-10 00:32:31 +01:00
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")
2021-02-18 22:35:41 +01:00
})
it("should call the proper callbacks for 'install'", async () => {
2021-03-10 00:32:31 +01:00
require("../../src/browser/serviceWorker.ts")
emit("install")
2021-02-18 22:35:41 +01:00
expect(spy).toHaveBeenCalledWith("[Service Worker] installed")
expect(spy).toHaveBeenCalledTimes(1)
})
it("should do nothing when 'fetch' is called", async () => {
2021-03-10 00:32:31 +01:00
require("../../src/browser/serviceWorker.ts")
emit("fetch")
expect(spy).not.toHaveBeenCalled()
})
2021-02-18 22:35:41 +01:00
it("should call the proper callbacks for 'activate'", async () => {
2021-03-10 00:32:31 +01:00
require("../../src/browser/serviceWorker.ts")
emit("activate")
2021-02-18 22:35:41 +01:00
// Activate serviceWorker
expect(spy).toHaveBeenCalledWith("[Service Worker] activated")
expect(waitUntilSpy).toHaveBeenCalled()
expect(claimSpy).toHaveBeenCalled()
})
2021-02-18 22:35:41 +01:00
})