1
0
mirror of https://github.com/matrix-org/matrix-js-sdk.git synced 2025-07-31 15:24:23 +03:00

test typescriptification - misc (#2547)

* renamed:    spec/unit/login.spec.js -> spec/unit/login.spec.ts

* type test client

* renamed:    spec/unit/interactive-auth.spec.js -> spec/unit/interactive-auth.spec.ts

* fix ts issues in interactive-auth.spec

* renamed:    spec/unit/filter.spec.js -> spec/unit/filter.spec.ts

* fix ts in filter.spec

* renamed:    spec/unit/event.spec.js -> spec/unit/event.spec.ts

* ts in event.spec

* renamed:    spec/unit/pushprocessor.spec.js -> spec/unit/pushprocessor.spec.ts

* fix ts in pushprocessor.spec

* fix ts in realtime-callbacks.spec

* renamed:    spec/unit/content-repo.spec.js -> spec/unit/content-repo.spec.ts

* fix signature for getHttpUriForMxc

* pr fixes
This commit is contained in:
Kerry
2022-07-28 08:09:21 +02:00
committed by GitHub
parent 7cb3b40493
commit 75513d08de
8 changed files with 96 additions and 103 deletions

View File

@ -19,41 +19,41 @@ describe("ContentRepo", function() {
}); });
it("should return a download URL if no width/height/resize are specified", it("should return a download URL if no width/height/resize are specified",
function() { function() {
const mxcUri = "mxc://server.name/resourceid"; const mxcUri = "mxc://server.name/resourceid";
expect(getHttpUriForMxc(baseUrl, mxcUri)).toEqual( expect(getHttpUriForMxc(baseUrl, mxcUri)).toEqual(
baseUrl + "/_matrix/media/r0/download/server.name/resourceid", baseUrl + "/_matrix/media/r0/download/server.name/resourceid",
); );
}); });
it("should return the empty string for null input", function() { it("should return the empty string for null input", function() {
expect(getHttpUriForMxc(null)).toEqual(""); expect(getHttpUriForMxc(null, null)).toEqual("");
}); });
it("should return a thumbnail URL if a width/height/resize is specified", it("should return a thumbnail URL if a width/height/resize is specified",
function() { function() {
const mxcUri = "mxc://server.name/resourceid"; const mxcUri = "mxc://server.name/resourceid";
expect(getHttpUriForMxc(baseUrl, mxcUri, 32, 64, "crop")).toEqual( expect(getHttpUriForMxc(baseUrl, mxcUri, 32, 64, "crop")).toEqual(
baseUrl + "/_matrix/media/r0/thumbnail/server.name/resourceid" + baseUrl + "/_matrix/media/r0/thumbnail/server.name/resourceid" +
"?width=32&height=64&method=crop", "?width=32&height=64&method=crop",
); );
}); });
it("should put fragments from mxc:// URIs after any query parameters", it("should put fragments from mxc:// URIs after any query parameters",
function() { function() {
const mxcUri = "mxc://server.name/resourceid#automade"; const mxcUri = "mxc://server.name/resourceid#automade";
expect(getHttpUriForMxc(baseUrl, mxcUri, 32)).toEqual( expect(getHttpUriForMxc(baseUrl, mxcUri, 32)).toEqual(
baseUrl + "/_matrix/media/r0/thumbnail/server.name/resourceid" + baseUrl + "/_matrix/media/r0/thumbnail/server.name/resourceid" +
"?width=32#automade", "?width=32#automade",
); );
}); });
it("should put fragments from mxc:// URIs at the end of the HTTP URI", it("should put fragments from mxc:// URIs at the end of the HTTP URI",
function() { function() {
const mxcUri = "mxc://server.name/resourceid#automade"; const mxcUri = "mxc://server.name/resourceid#automade";
expect(getHttpUriForMxc(baseUrl, mxcUri)).toEqual( expect(getHttpUriForMxc(baseUrl, mxcUri)).toEqual(
baseUrl + "/_matrix/media/r0/download/server.name/resourceid#automade", baseUrl + "/_matrix/media/r0/download/server.name/resourceid#automade",
); );
}); });
}); });
}); });

View File

@ -1,6 +1,6 @@
/* /*
Copyright 2017 New Vector Ltd Copyright 2017 New Vector Ltd
Copyright 2019 The Matrix.org Foundation C.I.C. Copyright 2019, 2022 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License"); Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. you may not use this file except in compliance with the License.
@ -15,16 +15,16 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { logger } from "../../src/logger";
import { MatrixEvent } from "../../src/models/event"; import { MatrixEvent } from "../../src/models/event";
describe("MatrixEvent", () => { describe("MatrixEvent", () => {
describe(".attemptDecryption", () => { describe(".attemptDecryption", () => {
let encryptedEvent; let encryptedEvent;
const eventId = 'test_encrypted_event';
beforeEach(() => { beforeEach(() => {
encryptedEvent = new MatrixEvent({ encryptedEvent = new MatrixEvent({
id: 'test_encrypted_event', event_id: eventId,
type: 'm.room.encrypted', type: 'm.room.encrypted',
content: { content: {
ciphertext: 'secrets', ciphertext: 'secrets',
@ -32,45 +32,34 @@ describe("MatrixEvent", () => {
}); });
}); });
it('should retry decryption if a retry is queued', () => { it('should retry decryption if a retry is queued', async () => {
let callCount = 0; const eventAttemptDecryptionSpy = jest.spyOn(encryptedEvent, 'attemptDecryption');
let prom2;
let prom2Fulfilled = false;
const crypto = { const crypto = {
decryptEvent: function() { decryptEvent: jest.fn()
++callCount; .mockImplementationOnce(() => {
logger.log(`decrypt: ${callCount}`);
if (callCount == 1) {
// schedule a second decryption attempt while // schedule a second decryption attempt while
// the first one is still running. // the first one is still running.
prom2 = encryptedEvent.attemptDecryption(crypto); encryptedEvent.attemptDecryption(crypto);
prom2.then(() => prom2Fulfilled = true);
const error = new Error("nope"); const error = new Error("nope");
error.name = 'DecryptionError'; error.name = 'DecryptionError';
return Promise.reject(error); return Promise.reject(error);
} else { })
expect(prom2Fulfilled).toBe( .mockImplementationOnce(() => {
false, 'second attemptDecryption resolved too soon');
return Promise.resolve({ return Promise.resolve({
clearEvent: { clearEvent: {
type: 'm.room.message', type: 'm.room.message',
}, },
}); });
} }),
},
}; };
return encryptedEvent.attemptDecryption(crypto).then(() => { await encryptedEvent.attemptDecryption(crypto);
expect(callCount).toEqual(2);
expect(encryptedEvent.getType()).toEqual('m.room.message');
// make sure the second attemptDecryption resolves expect(eventAttemptDecryptionSpy).toHaveBeenCalledTimes(2);
return prom2; expect(crypto.decryptEvent).toHaveBeenCalledTimes(2);
}); expect(encryptedEvent.getType()).toEqual('m.room.message');
}); });
}); });
}); });

View File

@ -1,9 +1,9 @@
import { Filter } from "../../src/filter"; import { Filter, IFilterDefinition } from "../../src/filter";
describe("Filter", function() { describe("Filter", function() {
const filterId = "f1lt3ring15g00d4ursoul"; const filterId = "f1lt3ring15g00d4ursoul";
const userId = "@sir_arthur_david:humming.tiger"; const userId = "@sir_arthur_david:humming.tiger";
let filter; let filter: Filter;
beforeEach(function() { beforeEach(function() {
filter = new Filter(userId); filter = new Filter(userId);
@ -37,7 +37,7 @@ describe("Filter", function() {
describe("setDefinition/getDefinition", function() { describe("setDefinition/getDefinition", function() {
it("should set and get the filter body", function() { it("should set and get the filter body", function() {
const definition = { const definition = {
event_format: "client", event_format: "client" as IFilterDefinition['event_format'],
}; };
filter.setDefinition(definition); filter.setDefinition(definition);
expect(filter.getDefinition()).toEqual(definition); expect(filter.getDefinition()).toEqual(definition);

View File

@ -15,8 +15,9 @@ See the License for the specific language governing permissions and
limitations under the License. limitations under the License.
*/ */
import { MatrixClient } from "../../src/client";
import { logger } from "../../src/logger"; import { logger } from "../../src/logger";
import { InteractiveAuth } from "../../src/interactive-auth"; import { InteractiveAuth, AuthType } from "../../src/interactive-auth";
import { MatrixError } from "../../src/http-api"; import { MatrixError } from "../../src/http-api";
import { sleep } from "../../src/utils"; import { sleep } from "../../src/utils";
import { randomString } from "../../src/randomstring"; import { randomString } from "../../src/randomstring";
@ -29,38 +30,40 @@ class FakeClient {
} }
} }
const getFakeClient = (): MatrixClient => new FakeClient() as unknown as MatrixClient;
describe("InteractiveAuth", function() { describe("InteractiveAuth", function() {
it("should start an auth stage and complete it", function() { it("should start an auth stage and complete it", function() {
const doRequest = jest.fn(); const doRequest = jest.fn();
const stateUpdated = jest.fn(); const stateUpdated = jest.fn();
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest: doRequest, doRequest: doRequest,
stateUpdated: stateUpdated, stateUpdated: stateUpdated,
requestEmailToken: jest.fn(),
authData: { authData: {
session: "sessionId", session: "sessionId",
flows: [ flows: [
{ stages: ["logintype"] }, { stages: [AuthType.Password] },
], ],
params: { params: {
"logintype": { param: "aa" }, [AuthType.Password]: { param: "aa" },
}, },
}, },
}); });
expect(ia.getSessionId()).toEqual("sessionId"); expect(ia.getSessionId()).toEqual("sessionId");
expect(ia.getStageParams("logintype")).toEqual({ expect(ia.getStageParams(AuthType.Password)).toEqual({
param: "aa", param: "aa",
}); });
// first we expect a call here // first we expect a call here
stateUpdated.mockImplementation(function(stage) { stateUpdated.mockImplementation(function(stage) {
logger.log('aaaa'); logger.log('aaaa');
expect(stage).toEqual("logintype"); expect(stage).toEqual(AuthType.Password);
ia.submitAuthDict({ ia.submitAuthDict({
type: "logintype", type: AuthType.Password,
foo: "bar",
}); });
}); });
@ -70,8 +73,7 @@ describe("InteractiveAuth", function() {
logger.log('cccc'); logger.log('cccc');
expect(authData).toEqual({ expect(authData).toEqual({
session: "sessionId", session: "sessionId",
type: "logintype", type: AuthType.Password,
foo: "bar",
}); });
return Promise.resolve(requestRes); return Promise.resolve(requestRes);
}); });
@ -86,15 +88,17 @@ describe("InteractiveAuth", function() {
it("should make a request if no authdata is provided", function() { it("should make a request if no authdata is provided", function() {
const doRequest = jest.fn(); const doRequest = jest.fn();
const stateUpdated = jest.fn(); const stateUpdated = jest.fn();
const requestEmailToken = jest.fn();
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
stateUpdated: stateUpdated, stateUpdated,
doRequest: doRequest, doRequest,
requestEmailToken,
}); });
expect(ia.getSessionId()).toBe(undefined); expect(ia.getSessionId()).toBe(undefined);
expect(ia.getStageParams("logintype")).toBe(undefined); expect(ia.getStageParams(AuthType.Password)).toBe(undefined);
// first we expect a call to doRequest // first we expect a call to doRequest
doRequest.mockImplementation(function(authData) { doRequest.mockImplementation(function(authData) {
@ -103,10 +107,10 @@ describe("InteractiveAuth", function() {
const err = new MatrixError({ const err = new MatrixError({
session: "sessionId", session: "sessionId",
flows: [ flows: [
{ stages: ["logintype"] }, { stages: [AuthType.Password] },
], ],
params: { params: {
"logintype": { param: "aa" }, [AuthType.Password]: { param: "aa" },
}, },
}); });
err.httpStatus = 401; err.httpStatus = 401;
@ -116,9 +120,9 @@ describe("InteractiveAuth", function() {
// .. which should be followed by a call to stateUpdated // .. which should be followed by a call to stateUpdated
const requestRes = { "a": "b" }; const requestRes = { "a": "b" };
stateUpdated.mockImplementation(function(stage) { stateUpdated.mockImplementation(function(stage) {
expect(stage).toEqual("logintype"); expect(stage).toEqual(AuthType.Password);
expect(ia.getSessionId()).toEqual("sessionId"); expect(ia.getSessionId()).toEqual("sessionId");
expect(ia.getStageParams("logintype")).toEqual({ expect(ia.getStageParams(AuthType.Password)).toEqual({
param: "aa", param: "aa",
}); });
@ -127,15 +131,13 @@ describe("InteractiveAuth", function() {
logger.log("request2", authData); logger.log("request2", authData);
expect(authData).toEqual({ expect(authData).toEqual({
session: "sessionId", session: "sessionId",
type: "logintype", type: AuthType.Password,
foo: "bar",
}); });
return Promise.resolve(requestRes); return Promise.resolve(requestRes);
}); });
ia.submitAuthDict({ ia.submitAuthDict({
type: "logintype", type: AuthType.Password,
foo: "bar",
}); });
}); });
@ -149,11 +151,13 @@ describe("InteractiveAuth", function() {
it("should start an auth stage and reject if no auth flow", function() { it("should start an auth stage and reject if no auth flow", function() {
const doRequest = jest.fn(); const doRequest = jest.fn();
const stateUpdated = jest.fn(); const stateUpdated = jest.fn();
const requestEmailToken = jest.fn();
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest: doRequest, doRequest,
stateUpdated: stateUpdated, stateUpdated,
requestEmailToken,
}); });
doRequest.mockImplementation(function(authData) { doRequest.mockImplementation(function(authData) {
@ -163,7 +167,7 @@ describe("InteractiveAuth", function() {
session: "sessionId", session: "sessionId",
flows: [], flows: [],
params: { params: {
"logintype": { param: "aa" }, [AuthType.Password]: { param: "aa" },
}, },
}); });
err.httpStatus = 401; err.httpStatus = 401;
@ -183,7 +187,7 @@ describe("InteractiveAuth", function() {
requestEmailToken.mockImplementation(async () => ({ sid: "" })); requestEmailToken.mockImplementation(async () => ({ sid: "" }));
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest, stateUpdated, requestEmailToken, doRequest, stateUpdated, requestEmailToken,
}); });
@ -210,7 +214,7 @@ describe("InteractiveAuth", function() {
requestEmailToken.mockImplementation(async () => ({ sid: "" })); requestEmailToken.mockImplementation(async () => ({ sid: "" }));
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest, stateUpdated, requestEmailToken, doRequest, stateUpdated, requestEmailToken,
}); });
@ -239,7 +243,7 @@ describe("InteractiveAuth", function() {
}); });
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest, stateUpdated, requestEmailToken, doRequest, stateUpdated, requestEmailToken,
}); });
@ -253,7 +257,7 @@ describe("InteractiveAuth", function() {
requestEmailToken.mockImplementation(() => sleep(500, { sid: "" })); requestEmailToken.mockImplementation(() => sleep(500, { sid: "" }));
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest, stateUpdated, requestEmailToken, doRequest, stateUpdated, requestEmailToken,
}); });
@ -269,7 +273,7 @@ describe("InteractiveAuth", function() {
requestEmailToken.mockImplementation(() => sleep(500, { sid })); requestEmailToken.mockImplementation(() => sleep(500, { sid }));
const ia = new InteractiveAuth({ const ia = new InteractiveAuth({
matrixClient: new FakeClient(), matrixClient: getFakeClient(),
doRequest, stateUpdated, requestEmailToken, doRequest, stateUpdated, requestEmailToken,
}); });

View File

@ -1,7 +1,7 @@
import { TestClient } from '../TestClient'; import { TestClient } from '../TestClient';
describe('Login request', function() { describe('Login request', function() {
let client; let client: TestClient;
beforeEach(function() { beforeEach(function() {
client = new TestClient(); client = new TestClient();

View File

@ -1,15 +1,15 @@
import * as utils from "../test-utils/test-utils"; import * as utils from "../test-utils/test-utils";
import { PushProcessor } from "../../src/pushprocessor"; import { PushProcessor } from "../../src/pushprocessor";
import { EventType } from "../../src"; import { EventType, MatrixClient, MatrixEvent } from "../../src";
describe('NotificationService', function() { describe('NotificationService', function() {
const testUserId = "@ali:matrix.org"; const testUserId = "@ali:matrix.org";
const testDisplayName = "Alice M"; const testDisplayName = "Alice M";
const testRoomId = "!fl1bb13:localhost"; const testRoomId = "!fl1bb13:localhost";
let testEvent; let testEvent: MatrixEvent;
let pushProcessor; let pushProcessor: PushProcessor;
// These would be better if individual rules were configured in the tests themselves. // These would be better if individual rules were configured in the tests themselves.
const matrixClient = { const matrixClient = {
@ -196,7 +196,7 @@ describe('NotificationService', function() {
], ],
}, },
}, },
}; } as unknown as MatrixClient;
beforeEach(function() { beforeEach(function() {
testEvent = utils.mkEvent({ testEvent = utils.mkEvent({

View File

@ -21,7 +21,7 @@ describe("realtime-callbacks", function() {
it("should default to a zero timeout", function() { it("should default to a zero timeout", function() {
const callback = jest.fn(); const callback = jest.fn();
callbacks.setTimeout(callback); callbacks.setTimeout(callback, 0);
expect(callback).not.toHaveBeenCalled(); expect(callback).not.toHaveBeenCalled();
tick(0); tick(0);
@ -38,11 +38,11 @@ describe("realtime-callbacks", function() {
it("should set 'this' to the global object", function() { it("should set 'this' to the global object", function() {
let passed = false; let passed = false;
const callback = function() { const callback = function() {
expect(this).toBe(global); // eslint-disable-line @babel/no-invalid-this expect(this).toBe(global); // eslint-disable-line @typescript-eslint/no-invalid-this
expect(this.console).toBeTruthy(); // eslint-disable-line @babel/no-invalid-this expect(this.console).toBeTruthy(); // eslint-disable-line @typescript-eslint/no-invalid-this
passed = true; passed = true;
}; };
callbacks.setTimeout(callback); callbacks.setTimeout(callback, 0);
tick(0); tick(0);
expect(passed).toBe(true); expect(passed).toBe(true);
}); });
@ -92,7 +92,7 @@ describe("realtime-callbacks", function() {
expect(callback2).not.toHaveBeenCalled(); expect(callback2).not.toHaveBeenCalled();
}); });
callbacks.setTimeout(callback1); callbacks.setTimeout(callback1, 0);
callbacks.setTimeout(callback2, -100); callbacks.setTimeout(callback2, -100);
expect(callback1).not.toHaveBeenCalled(); expect(callback1).not.toHaveBeenCalled();
@ -109,14 +109,14 @@ describe("realtime-callbacks", function() {
expect(callback2).not.toHaveBeenCalled(); expect(callback2).not.toHaveBeenCalled();
}); });
callbacks.setTimeout(callback1); callbacks.setTimeout(callback1, 1);
expect(callback1).not.toHaveBeenCalled(); expect(callback1).not.toHaveBeenCalled();
expect(callback2).not.toHaveBeenCalled(); expect(callback2).not.toHaveBeenCalled();
tick(0); tick(1);
expect(callback1).toHaveBeenCalled(); expect(callback1).toHaveBeenCalled();
// the fake timer won't actually run callbacks registered during // the fake timer won't actually run callbacks registered during
// one tick until the next tick. // one tick until the next tick.
tick(1); tick(2);
expect(callback2).toHaveBeenCalled(); expect(callback2).toHaveBeenCalled();
}); });
@ -139,9 +139,9 @@ describe("realtime-callbacks", function() {
describe("cancelTimeout", function() { describe("cancelTimeout", function() {
it("should cancel a pending timeout", function() { it("should cancel a pending timeout", function() {
const callback = jest.fn(); const callback = jest.fn();
const k = callbacks.setTimeout(callback); const k = callbacks.setTimeout(callback, 10);
callbacks.clearTimeout(k); callbacks.clearTimeout(k);
tick(0); tick(11);
expect(callback).not.toHaveBeenCalled(); expect(callback).not.toHaveBeenCalled();
}); });

View File

@ -36,9 +36,9 @@ import * as utils from "./utils";
export function getHttpUriForMxc( export function getHttpUriForMxc(
baseUrl: string, baseUrl: string,
mxc: string, mxc: string,
width: number, width?: number,
height: number, height?: number,
resizeMethod: string, resizeMethod?: string,
allowDirectLinks = false, allowDirectLinks = false,
): string { ): string {
if (typeof mxc !== "string" || !mxc) { if (typeof mxc !== "string" || !mxc) {