Skip to content

Commit 017dfb6

Browse files
authored
Write additional tests (#22802)
* Write additional tests * Make Sonar happier
1 parent a4f9e7a commit 017dfb6

File tree

10 files changed

+87
-40
lines changed

10 files changed

+87
-40
lines changed

src/favicon.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ export default class Favicon {
5454

5555
private isReady = false;
5656
// callback to run once isReady is asserted, allows for a badge to be queued for when it can be shown
57-
private readyCb = () => {};
57+
private readyCb?: () => void;
5858

5959
constructor(params: Partial<IParams> = {}) {
6060
this.params = { ...defaults, ...params };
@@ -180,7 +180,7 @@ export default class Favicon {
180180
private ready() {
181181
if (this.isReady) return;
182182
this.isReady = true;
183-
this.readyCb();
183+
this.readyCb?.();
184184
}
185185

186186
private setIcon(canvas) {
@@ -230,9 +230,9 @@ export default class Favicon {
230230
private static getLinks() {
231231
const icons: HTMLLinkElement[] = [];
232232
const links = window.document.getElementsByTagName("head")[0].getElementsByTagName("link");
233-
for (let i = 0; i < links.length; i++) {
234-
if ((/(^|\s)icon(\s|$)/i).test(links[i].getAttribute("rel"))) {
235-
icons.push(links[i]);
233+
for (const link of links) {
234+
if ((/(^|\s)icon(\s|$)/i).test(link.getAttribute("rel"))) {
235+
icons.push(link);
236236
}
237237
}
238238
return icons;

src/vector/init.tsx

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,8 @@ export function loadOlm(): Promise<void> {
9292
locateFile: () => olmWasmPath,
9393
}).then(() => {
9494
logger.log("Using WebAssembly Olm");
95-
}).catch((e) => {
96-
logger.log("Failed to load Olm: trying legacy version", e);
95+
}).catch((wasmLoadError) => {
96+
logger.log("Failed to load Olm: trying legacy version", wasmLoadError);
9797
return new Promise((resolve, reject) => {
9898
const s = document.createElement('script');
9999
s.src = 'olm_legacy.js'; // XXX: This should be cache-busted too
@@ -106,8 +106,8 @@ export function loadOlm(): Promise<void> {
106106
return window.Olm.init();
107107
}).then(() => {
108108
logger.log("Using legacy Olm");
109-
}).catch((e) => {
110-
logger.log("Both WebAssembly and asm.js Olm failed!", e);
109+
}).catch((legacyLoadError) => {
110+
logger.log("Both WebAssembly and asm.js Olm failed!", legacyLoadError);
111111
});
112112
});
113113
}

src/vector/platform/IPCManager.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export class IPCManager {
4848
return deferred.promise;
4949
}
5050

51-
private onIpcReply = (ev: {}, payload: IPCPayload): void => {
51+
private onIpcReply = (_ev: {}, payload: IPCPayload): void => {
5252
if (payload.id === undefined) {
5353
logger.warn("Ignoring IPC reply with no ID");
5454
return;

src/vector/platform/VectorBasePlatform.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ export default abstract class VectorBasePlatform extends BasePlatform {
4747
if (this._favicon) {
4848
return this._favicon;
4949
}
50-
return this._favicon = new Favicon();
50+
this._favicon = new Favicon();
51+
return this._favicon;
5152
}
5253

5354
private updateFavicon() {

src/vector/platform/WebPlatform.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ export default class WebPlatform extends VectorBasePlatform {
8080
// annoyingly, the latest spec says this returns a
8181
// promise, but this is only supported in Chrome 46
8282
// and Firefox 47, so adapt the callback API.
83-
return new Promise(function(resolve, reject) {
83+
return new Promise(function(resolve) {
8484
window.Notification.requestPermission((result) => {
8585
resolve(result);
8686
});

src/vector/rageshakesetup.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export function initRageshake() {
3939
logger.log("To fix line numbers in Chrome: " +
4040
"Meatball menu → Settings → Ignore list → Add /rageshake\\.js$");
4141

42-
window.addEventListener('beforeunload', (e) => {
42+
window.addEventListener('beforeunload', () => {
4343
logger.log('element-web closing');
4444
// try to flush the logs to indexeddb
4545
rageshake.flush();

src/vector/routing.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ function routeUrl(location: Location) {
4141
(window.matrixChat as MatrixChatType).showScreen(s.screen, s.params);
4242
}
4343

44-
function onHashChange(ev: HashChangeEvent) {
44+
function onHashChange() {
4545
if (decodeURIComponent(window.location.hash) === lastLocationHashSet) {
4646
// we just set this: no need to route it!
4747
return;

test/unit-tests/vector/getconfig-test.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,16 @@ describe('getVectorConfig()', () => {
4848
it('requests specific config for document domain', async () => {
4949
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(specificConfig))
5050
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
51-
51+
5252
await getVectorConfig();
5353

5454
expect(request.mock.calls[0][0]).toEqual({ method: "GET", url: 'config.app.element.io.json', qs: { cachebuster: now } })
5555
});
56-
56+
5757
it('adds trailing slash to relativeLocation when not an empty string', async () => {
5858
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(specificConfig))
5959
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
60-
60+
6161
await getVectorConfig('..');
6262

6363
expect(request.mock.calls[0][0]).toEqual(expect.objectContaining({ url: '../config.app.element.io.json' }))
@@ -67,47 +67,47 @@ describe('getVectorConfig()', () => {
6767
it('returns parsed specific config when it is non-empty', async () => {
6868
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(specificConfig))
6969
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
70-
70+
7171
const result = await getVectorConfig();
7272
expect(result).toEqual(specificConfig);
7373
});
7474

7575
it('returns general config when specific config succeeds but is empty', async () => {
7676
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify({}))
7777
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
78-
78+
7979
const result = await getVectorConfig();
8080
expect(result).toEqual(generalConfig);
8181
});
8282

8383
it('returns general config when specific config 404s', async () => {
8484
setRequestMockImplementationOnce(undefined, { status: 404 })
8585
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
86-
86+
8787
const result = await getVectorConfig();
8888
expect(result).toEqual(generalConfig);
8989
});
9090

9191
it('returns general config when specific config is fetched from a file and is empty', async () => {
9292
setRequestMockImplementationOnce(undefined, { status: 0 }, '')
9393
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
94-
94+
9595
const result = await getVectorConfig();
9696
expect(result).toEqual(generalConfig);
9797
});
9898

9999
it('returns general config when specific config returns a non-200 status', async () => {
100100
setRequestMockImplementationOnce(undefined, { status: 401 })
101101
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
102-
102+
103103
const result = await getVectorConfig();
104104
expect(result).toEqual(generalConfig);
105105
});
106106

107107
it('returns general config when specific config returns an error', async () => {
108108
setRequestMockImplementationOnce('err1')
109109
setRequestMockImplementationOnce(undefined, { status: 200 }, JSON.stringify(generalConfig))
110-
110+
111111
const result = await getVectorConfig();
112112
expect(result).toEqual(generalConfig);
113113
});
@@ -119,4 +119,12 @@ describe('getVectorConfig()', () => {
119119
await expect(() => getVectorConfig()).rejects.toEqual({"err": "err-general", "response": undefined});
120120
});
121121

122+
it('rejects with an error when config is invalid JSON', async () => {
123+
setRequestMockImplementationOnce('err-specific');
124+
setRequestMockImplementationOnce(undefined, { status: 200 }, '{"invalid": "json",}');
125+
126+
await expect(() => getVectorConfig()).rejects.toEqual({
127+
err: new SyntaxError("Unexpected token } in JSON at position 19"),
128+
});
129+
});
122130
});
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import PWAPlatform from "../../../../src/vector/platform/PWAPlatform";
18+
19+
describe('PWAPlatform', () => {
20+
beforeEach(() => {
21+
jest.clearAllMocks();
22+
});
23+
24+
describe("setNotificationCount", () => {
25+
it("should call Navigator::setAppBadge", () => {
26+
navigator.setAppBadge = jest.fn().mockResolvedValue(undefined);
27+
const platform = new PWAPlatform();
28+
expect(navigator.setAppBadge).not.toHaveBeenCalled();
29+
platform.setNotificationCount(123);
30+
expect(navigator.setAppBadge).toHaveBeenCalledWith(123);
31+
});
32+
});
33+
});

test/unit-tests/vector/platform/WebPlatform-test.ts

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ describe('WebPlatform', () => {
3030
expect(platform.getHumanReadableName()).toEqual('Web Platform');
3131
});
3232

33+
it('registers service worker', () => {
34+
// @ts-ignore - mocking readonly object
35+
navigator.serviceWorker = { register: jest.fn() };
36+
new WebPlatform();
37+
expect(navigator.serviceWorker.register).toHaveBeenCalled();
38+
});
39+
3340
describe('notification support', () => {
3441
const mockNotification = {
3542
requestPermission: jest.fn(),
@@ -50,7 +57,7 @@ describe('WebPlatform', () => {
5057
it('supportsNotifications returns true when platform supports notifications', () => {
5158
expect(new WebPlatform().supportsNotifications()).toBe(true);
5259
});
53-
60+
5461
it('maySendNotifications returns true when notification permissions are not granted', () => {
5562
expect(new WebPlatform().maySendNotifications()).toBe(false);
5663
});
@@ -109,78 +116,76 @@ describe('WebPlatform', () => {
109116
});
110117

111118
describe('pollForUpdate()', () => {
112-
113119
it('should return not available and call showNoUpdate when current version matches most recent version', async () => {
114120
process.env.VERSION = prodVersion;
115121
setRequestMockImplementation(undefined, { status: 200}, prodVersion);
116122
const platform = new WebPlatform();
117-
123+
118124
const showUpdate = jest.fn();
119125
const showNoUpdate = jest.fn();
120126
const result = await platform.pollForUpdate(showUpdate, showNoUpdate);
121-
127+
122128
expect(result).toEqual({ status: UpdateCheckStatus.NotAvailable });
123129
expect(showUpdate).not.toHaveBeenCalled();
124130
expect(showNoUpdate).toHaveBeenCalled();
125131
});
126-
132+
127133
it('should strip v prefix from versions before comparing', async () => {
128134
process.env.VERSION = prodVersion;
129135
setRequestMockImplementation(undefined, { status: 200}, `v${prodVersion}`);
130136
const platform = new WebPlatform();
131-
137+
132138
const showUpdate = jest.fn();
133139
const showNoUpdate = jest.fn();
134140
const result = await platform.pollForUpdate(showUpdate, showNoUpdate);
135-
141+
136142
// versions only differ by v prefix, no update
137143
expect(result).toEqual({ status: UpdateCheckStatus.NotAvailable });
138144
expect(showUpdate).not.toHaveBeenCalled();
139145
expect(showNoUpdate).toHaveBeenCalled();
140146
});
141-
147+
142148
it('should return ready and call showUpdate when current version differs from most recent version', async () => {
143149
process.env.VERSION = '0.0.0'; // old version
144150
setRequestMockImplementation(undefined, { status: 200}, prodVersion);
145151
const platform = new WebPlatform();
146-
152+
147153
const showUpdate = jest.fn();
148154
const showNoUpdate = jest.fn();
149155
const result = await platform.pollForUpdate(showUpdate, showNoUpdate);
150-
156+
151157
expect(result).toEqual({ status: UpdateCheckStatus.Ready });
152158
expect(showUpdate).toHaveBeenCalledWith('0.0.0', prodVersion);
153159
expect(showNoUpdate).not.toHaveBeenCalled();
154160
});
155-
161+
156162
it('should return ready without showing update when user registered in last 24', async () => {
157163
process.env.VERSION = '0.0.0'; // old version
158164
jest.spyOn(MatrixClientPeg, 'userRegisteredWithinLastHours').mockReturnValue(true);
159165
setRequestMockImplementation(undefined, { status: 200}, prodVersion);
160166
const platform = new WebPlatform();
161-
167+
162168
const showUpdate = jest.fn();
163169
const showNoUpdate = jest.fn();
164170
const result = await platform.pollForUpdate(showUpdate, showNoUpdate);
165-
171+
166172
expect(result).toEqual({ status: UpdateCheckStatus.Ready });
167173
expect(showUpdate).not.toHaveBeenCalled();
168174
expect(showNoUpdate).not.toHaveBeenCalled();
169175
});
170-
176+
171177
it('should return error when version check fails', async () => {
172178
setRequestMockImplementation('oups');
173179
const platform = new WebPlatform();
174-
180+
175181
const showUpdate = jest.fn();
176182
const showNoUpdate = jest.fn();
177183
const result = await platform.pollForUpdate(showUpdate, showNoUpdate);
178-
184+
179185
expect(result).toEqual({ status: UpdateCheckStatus.Error, detail: 'Unknown Error' });
180186
expect(showUpdate).not.toHaveBeenCalled();
181187
expect(showNoUpdate).not.toHaveBeenCalled();
182188
});
183189
});
184-
185190
});
186191
});

0 commit comments

Comments
 (0)