1
0
mirror of https://github.com/coder/code-server.git synced 2024-12-04 15:00:38 +08:00
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-19 05:35:41 +08:00
describe("serviceWorker", () => {
let listeners: Listener[] = []
2021-02-19 05:35:41 +08: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-19 05:35:41 +08:00
beforeEach(() => {
claimSpy = jest.fn()
2021-02-19 05:35:41 +08: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-19 05:35:41 +08:00
})
afterEach(() => {
jest.restoreAllMocks()
jest.resetModules()
spy.mockClear()
claimSpy.mockClear()
// Clear all the listeners
listeners = []
2021-02-19 05:35:41 +08:00
})
it("should add 3 listeners: install, activate and fetch", () => {
2021-03-10 07:32:31 +08: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-19 05:35:41 +08:00
})
it("should call the proper callbacks for 'install'", async () => {
2021-03-10 07:32:31 +08:00
require("../../src/browser/serviceWorker.ts")
emit("install")
2021-02-19 05:35:41 +08:00
expect(spy).toHaveBeenCalledWith("[Service Worker] installed")
expect(spy).toHaveBeenCalledTimes(1)
})
it("should do nothing when 'fetch' is called", async () => {
2021-03-10 07:32:31 +08:00
require("../../src/browser/serviceWorker.ts")
emit("fetch")
expect(spy).not.toHaveBeenCalled()
})
2021-02-19 05:35:41 +08:00
it("should call the proper callbacks for 'activate'", async () => {
2021-03-10 07:32:31 +08:00
require("../../src/browser/serviceWorker.ts")
emit("activate")
2021-02-19 05:35:41 +08:00
// Activate serviceWorker
expect(spy).toHaveBeenCalledWith("[Service Worker] activated")
expect(waitUntilSpy).toHaveBeenCalled()
expect(claimSpy).toHaveBeenCalled()
})
2021-02-19 05:35:41 +08:00
})