fix(service-worker): listen for messages on the right event source (#19954)

Currently, the SwUpdate service doesn't receive messages from the SW.
This is because it attempts to subscribe to the 'message' event on
ServiceWorkerRegistration, when really messages are emitted by the
ServiceWorkerContainer.

This change moves to listening on ServiceWorkerContainer and changes
the mocks to reflect the way the browser actually works.

PR Close #19954
This commit is contained in:
Alex Rickabaugh
2017-10-26 10:29:36 -07:00
committed by Matias Niemelä
parent 703fcda590
commit 5adb7c9669
4 changed files with 28 additions and 35 deletions

View File

@ -10,17 +10,26 @@ import {Subject} from 'rxjs/Subject';
export class MockServiceWorkerContainer {
private onControllerChange: Function[] = [];
private onMessage: Function[] = [];
private registration: MockServiceWorkerRegistration|null = null;
controller: MockServiceWorker|null = null;
messages = new Subject();
addEventListener(event: 'controllerchange', handler: Function) {
this.onControllerChange.push(handler);
addEventListener(event: 'controllerchange'|'message', handler: Function) {
if (event === 'controllerchange') {
this.onControllerChange.push(handler);
} else if (event === 'message') {
this.onMessage.push(handler);
}
}
removeEventListener(event: 'controllerchange', handler: Function) {
this.onControllerChange = this.onControllerChange.filter(h => h !== handler);
if (event === 'controllerchange') {
this.onControllerChange = this.onControllerChange.filter(h => h !== handler);
} else if (event === 'message') {
this.onMessage = this.onMessage.filter(h => h !== handler);
}
}
async register(url: string): Promise<void> { return; }
@ -36,6 +45,12 @@ export class MockServiceWorkerContainer {
get mockRegistration(): Promise<MockServiceWorkerRegistration> {
return Promise.resolve(this.registration !);
}
sendMessage(value: Object): void {
this.onMessage.forEach(onMessage => onMessage({
data: value,
}));
}
}
export class MockServiceWorker {
@ -44,21 +59,4 @@ export class MockServiceWorker {
postMessage(value: Object) { this.mock.messages.next(value); }
}
export class MockServiceWorkerRegistration {
private onMessage: Function[] = [];
messages: Object[] = [];
constructor() {}
addEventListener(event: 'message', handler: Function) { this.onMessage.push(handler); }
removeEventListener(event: 'message', handler: Function) {
this.onMessage = this.onMessage.filter(h => h !== handler);
}
sendMessage(value: Object): void {
this.onMessage.forEach(onMessage => onMessage({
data: value,
}));
}
}
export class MockServiceWorkerRegistration {}