| 54 | export type SwTestHarness = SwTestHarnessImpl & ServiceWorkerGlobalScope; |
| 55 | |
| 56 | export class SwTestHarnessImpl |
| 57 | extends Adapter<MockCacheStorage> |
| 58 | implements Partial<ServiceWorkerGlobalScope> |
| 59 | { |
| 60 | readonly clients = new MockClients(); |
| 61 | private eventHandlers = new Map<string, EventListener>(); |
| 62 | private skippedWaiting = false; |
| 63 | |
| 64 | private selfMessageQueue: any[] = []; |
| 65 | autoAdvanceTime = false; |
| 66 | unregistered: boolean = false; |
| 67 | readonly notifications: {title: string; options: Object}[] = []; |
| 68 | readonly registration: ServiceWorkerRegistration = { |
| 69 | active: { |
| 70 | postMessage: (msg: any) => { |
| 71 | this.selfMessageQueue.push(msg); |
| 72 | }, |
| 73 | }, |
| 74 | scope: this.scopeUrl, |
| 75 | showNotification: (title: string, options: Object) => { |
| 76 | this.notifications.push({title, options}); |
| 77 | }, |
| 78 | unregister: () => { |
| 79 | this.unregistered = true; |
| 80 | }, |
| 81 | } as any; |
| 82 | |
| 83 | override get time() { |
| 84 | return this.mockTime; |
| 85 | } |
| 86 | |
| 87 | private mockTime = Date.now(); |
| 88 | |
| 89 | private timers: { |
| 90 | at: number; |
| 91 | duration: number; |
| 92 | fn: Function; |
| 93 | fired: boolean; |
| 94 | }[] = []; |
| 95 | |
| 96 | override parseUrl = parseUrl; |
| 97 | |
| 98 | constructor( |
| 99 | private server: MockServerState, |
| 100 | caches: MockCacheStorage, |
| 101 | scopeUrl: string, |
| 102 | ) { |
| 103 | super(scopeUrl, caches); |
| 104 | } |
| 105 | |
| 106 | async resolveSelfMessages(): Promise<void> { |
| 107 | while (this.selfMessageQueue.length > 0) { |
| 108 | const queue = this.selfMessageQueue; |
| 109 | this.selfMessageQueue = []; |
| 110 | await queue.reduce(async (previous, msg) => { |
| 111 | await previous; |
| 112 | await this.handleMessage(msg, null); |
| 113 | }, Promise.resolve()); |