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

Fix jest/valid-expects lints (#3586)

This commit is contained in:
Michael Telatynski
2023-07-12 18:11:52 +01:00
committed by GitHub
parent e82b5fe1db
commit b186d79dde
11 changed files with 66 additions and 49 deletions

View File

@ -66,9 +66,6 @@ module.exports = {
// Disabled tests are a reality for now but as soon as all of the xits are // Disabled tests are a reality for now but as soon as all of the xits are
// eliminated, we should enforce this. // eliminated, we should enforce this.
"jest/no-disabled-tests": "off", "jest/no-disabled-tests": "off",
// TODO: There are many tests with invalid expects that should be fixed,
// https://github.com/matrix-org/matrix-js-sdk/issues/2976
"jest/valid-expect": "off",
// Also treat "oldBackendOnly" as a test function. // Also treat "oldBackendOnly" as a test function.
// Used in some crypto tests. // Used in some crypto tests.
"jest/no-standalone-expect": [ "jest/no-standalone-expect": [

View File

@ -248,7 +248,7 @@ describe("getEventTimeline support", function () {
return startClient(httpBackend, client).then(function () { return startClient(httpBackend, client).then(function () {
const room = client.getRoom(roomId)!; const room = client.getRoom(roomId)!;
const timelineSet = room!.getTimelineSets()[0]; const timelineSet = room!.getTimelineSets()[0];
expect(client.getEventTimeline(timelineSet, "event")).rejects.toBeTruthy(); return expect(client.getEventTimeline(timelineSet, "event")).rejects.toBeTruthy();
}); });
}); });
@ -260,7 +260,18 @@ describe("getEventTimeline support", function () {
return startClient(httpBackend, client).then(() => { return startClient(httpBackend, client).then(() => {
const room = client.getRoom(roomId)!; const room = client.getRoom(roomId)!;
const timelineSet = room!.getTimelineSets()[0]; const timelineSet = room!.getTimelineSets()[0];
expect(client.getEventTimeline(timelineSet, "event")).rejects.toBeFalsy(); httpBackend.when("GET", `/rooms/${encodeURIComponent(roomId)}/context/event`).respond(200, () => ({
event: {
event_id: "event",
},
events_after: [],
events_before: [],
state: [],
}));
return Promise.all([
expect(client.getEventTimeline(timelineSet, "event")).resolves.toBeTruthy(),
httpBackend.flushAllExpected(),
]);
}); });
}); });
@ -271,7 +282,7 @@ describe("getEventTimeline support", function () {
return startClient(httpBackend, client).then(function () { return startClient(httpBackend, client).then(function () {
const timelineSet = new EventTimelineSet(undefined); const timelineSet = new EventTimelineSet(undefined);
expect(client.getEventTimeline(timelineSet, "event")).rejects.toBeTruthy(); return expect(client.getEventTimeline(timelineSet, "event")).rejects.toBeTruthy();
}); });
}); });
@ -778,7 +789,18 @@ describe("MatrixClient event timelines", function () {
return startClient(httpBackend, client).then(() => { return startClient(httpBackend, client).then(() => {
const room = client.getRoom(roomId)!; const room = client.getRoom(roomId)!;
const timelineSet = room.getTimelineSets()[0]; const timelineSet = room.getTimelineSets()[0];
expect(client.getLatestTimeline(timelineSet)).rejects.toBeFalsy(); httpBackend.when("GET", `/rooms/${encodeURIComponent(roomId)}/context/event`).respond(200, () => ({
event: {
event_id: "event",
},
events_after: [],
events_before: [],
state: [],
}));
return Promise.all([
expect(client.getEventTimeline(timelineSet, "event")).resolves.toBeTruthy(),
httpBackend.flushAllExpected(),
]);
}); });
}); });

View File

@ -1161,11 +1161,6 @@ describe("SlidingSync", () => {
httpBackend!.when("POST", syncUrl).check(pushTxn).respond(200, { pos: "f" }); // missing txn_id httpBackend!.when("POST", syncUrl).check(pushTxn).respond(200, { pos: "f" }); // missing txn_id
await httpBackend!.flushAllExpected(); await httpBackend!.flushAllExpected();
// attach rejection handlers now else if we do it later Jest treats that as an unhandled rejection
// which is a fail.
expect(failPromise).rejects.toEqual(gotTxnIds[0]);
expect(failPromise2).rejects.toEqual(gotTxnIds[1]);
const okPromise = slidingSync.setListRanges("a", [[0, 20]]); const okPromise = slidingSync.setListRanges("a", [[0, 20]]);
let txnId: string | undefined; let txnId: string | undefined;
httpBackend! httpBackend!
@ -1180,8 +1175,12 @@ describe("SlidingSync", () => {
txn_id: txnId, txn_id: txnId,
}; };
}); });
await httpBackend!.flushAllExpected(); await Promise.all([
await okPromise; expect(failPromise).rejects.toEqual(gotTxnIds[0]),
expect(failPromise2).rejects.toEqual(gotTxnIds[1]),
httpBackend!.flushAllExpected(),
okPromise,
]);
expect(txnId).toBeDefined(); expect(txnId).toBeDefined();
}); });
@ -1200,7 +1199,6 @@ describe("SlidingSync", () => {
// attach rejection handlers now else if we do it later Jest treats that as an unhandled rejection // attach rejection handlers now else if we do it later Jest treats that as an unhandled rejection
// which is a fail. // which is a fail.
expect(A).rejects.toEqual(gotTxnIds[0]);
const C = slidingSync.setListRanges("a", [[0, 20]]); const C = slidingSync.setListRanges("a", [[0, 20]]);
let pendingC = true; let pendingC = true;
@ -1217,9 +1215,12 @@ describe("SlidingSync", () => {
txn_id: gotTxnIds[1], txn_id: gotTxnIds[1],
}; };
}); });
await httpBackend!.flushAllExpected(); await Promise.all([
// A is rejected, see above expect(A).rejects.toEqual(gotTxnIds[0]),
expect(B).resolves.toEqual(gotTxnIds[1]); // B is resolved httpBackend!.flushAllExpected(),
// A is rejected, see above
expect(B).resolves.toEqual(gotTxnIds[1]), // B is resolved
]);
expect(pendingC).toBe(true); // C is pending still expect(pendingC).toBe(true); // C is pending still
}); });
it("should do nothing for unknown txn_ids", async () => { it("should do nothing for unknown txn_ids", async () => {

View File

@ -121,7 +121,7 @@ describe("refreshToken", () => {
body: { errcode: "M_UNRECOGNIZED" }, body: { errcode: "M_UNRECOGNIZED" },
}); });
expect(client.refreshToken("initial_refresh_token")).rejects.toMatchObject({ errcode: "M_UNRECOGNIZED" }); await expect(client.refreshToken("initial_refresh_token")).rejects.toMatchObject({ errcode: "M_UNRECOGNIZED" });
}); });
it("re-raises non-M_UNRECOGNIZED exceptions from /v3", async () => { it("re-raises non-M_UNRECOGNIZED exceptions from /v3", async () => {
@ -132,7 +132,7 @@ describe("refreshToken", () => {
throw new Error("/v1/refresh unexpectedly called"); throw new Error("/v1/refresh unexpectedly called");
}); });
expect(client.refreshToken("initial_refresh_token")).rejects.toMatchObject({ httpStatus: 429 }); await expect(client.refreshToken("initial_refresh_token")).rejects.toMatchObject({ httpStatus: 429 });
}); });
it("re-raises non-M_UNRECOGNIZED exceptions from /v1", async () => { it("re-raises non-M_UNRECOGNIZED exceptions from /v1", async () => {
@ -144,6 +144,6 @@ describe("refreshToken", () => {
}); });
fetchMock.postOnce(client.http.getUrl("/refresh", undefined, ClientPrefix.V1).toString(), 429); fetchMock.postOnce(client.http.getUrl("/refresh", undefined, ClientPrefix.V1).toString(), 429);
expect(client.refreshToken("initial_refresh_token")).rejects.toMatchObject({ httpStatus: 429 }); await expect(client.refreshToken("initial_refresh_token")).rejects.toMatchObject({ httpStatus: 429 });
}); });
}); });

View File

@ -66,7 +66,7 @@ describe("registerOidcClient()", () => {
fetchMockJest.post(registrationEndpoint, { fetchMockJest.post(registrationEndpoint, {
status: 500, status: 500,
}); });
expect(() => registerOidcClient(delegatedAuthConfig, clientName, baseUrl)).rejects.toThrow( await expect(() => registerOidcClient(delegatedAuthConfig, clientName, baseUrl)).rejects.toThrow(
OidcError.DynamicRegistrationFailed, OidcError.DynamicRegistrationFailed,
); );
}); });
@ -77,7 +77,7 @@ describe("registerOidcClient()", () => {
// no clientId in response // no clientId in response
body: "{}", body: "{}",
}); });
expect(() => registerOidcClient(delegatedAuthConfig, clientName, baseUrl)).rejects.toThrow( await expect(() => registerOidcClient(delegatedAuthConfig, clientName, baseUrl)).rejects.toThrow(
OidcError.DynamicRegistrationInvalid, OidcError.DynamicRegistrationInvalid,
); );
}); });

View File

@ -96,7 +96,7 @@ describe("ECDHv2", function () {
expect(aliceChecksum).toEqual(bobChecksum); expect(aliceChecksum).toEqual(bobChecksum);
expect(alice.connect()).rejects.toThrow(); await expect(alice.connect()).rejects.toThrow();
await alice.cancel(RendezvousFailureReason.Unknown); await alice.cancel(RendezvousFailureReason.Unknown);
await bob.cancel(RendezvousFailureReason.Unknown); await bob.cancel(RendezvousFailureReason.Unknown);
@ -120,9 +120,9 @@ describe("ECDHv2", function () {
alice.close(); alice.close();
expect(alice.connect()).rejects.toThrow(); await expect(alice.connect()).rejects.toThrow();
expect(alice.send({})).rejects.toThrow(); await expect(alice.send({})).rejects.toThrow();
expect(alice.receive()).rejects.toThrow(); await expect(alice.receive()).rejects.toThrow();
await alice.cancel(RendezvousFailureReason.Unknown); await alice.cancel(RendezvousFailureReason.Unknown);
await bob.cancel(RendezvousFailureReason.Unknown); await bob.cancel(RendezvousFailureReason.Unknown);
@ -146,10 +146,10 @@ describe("ECDHv2", function () {
// send a message without encryption // send a message without encryption
await aliceTransport.send({ iv: "dummy", ciphertext: "dummy" }); await aliceTransport.send({ iv: "dummy", ciphertext: "dummy" });
expect(bob.receive()).rejects.toThrow();
await alice.cancel(RendezvousFailureReason.Unknown); await alice.cancel(RendezvousFailureReason.Unknown);
await bob.cancel(RendezvousFailureReason.Unknown); await bob.cancel(RendezvousFailureReason.Unknown);
await expect(bob.receive()).rejects.toThrow();
}); });
it("ciphertext before set up", async function () { it("ciphertext before set up", async function () {
@ -164,9 +164,8 @@ describe("ECDHv2", function () {
await bobTransport.send({ iv: "dummy", ciphertext: "dummy" }); await bobTransport.send({ iv: "dummy", ciphertext: "dummy" });
expect(alice.receive()).rejects.toThrow();
await alice.cancel(RendezvousFailureReason.Unknown); await alice.cancel(RendezvousFailureReason.Unknown);
await expect(alice.receive()).rejects.toThrow();
}); });
}); });
}); });

View File

@ -172,7 +172,7 @@ describe("Rendezvous", function () {
const cancelPromise = aliceRz.cancel(RendezvousFailureReason.UserDeclined); const cancelPromise = aliceRz.cancel(RendezvousFailureReason.UserDeclined);
await httpBackend.flush(""); await httpBackend.flush("");
expect(cancelPromise).resolves.toBeUndefined(); await expect(cancelPromise).resolves.toBeUndefined();
httpBackend.verifyNoOutstandingExpectation(); httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequests(); httpBackend.verifyNoOutstandingRequests();
@ -603,7 +603,7 @@ describe("Rendezvous", function () {
it("device not online within timeout", async function () { it("device not online within timeout", async function () {
const { aliceRz } = await completeLogin({}); const { aliceRz } = await completeLogin({});
expect(aliceRz.verifyNewDeviceOnExistingDevice(1000)).rejects.toThrow(); await expect(aliceRz.verifyNewDeviceOnExistingDevice(1000)).rejects.toThrow();
}); });
it("device appears online within timeout", async function () { it("device appears online within timeout", async function () {
@ -627,7 +627,7 @@ describe("Rendezvous", function () {
getFingerprint: () => "bbbb", getFingerprint: () => "bbbb",
}; };
}, 1500); }, 1500);
expect(aliceRz.verifyNewDeviceOnExistingDevice(1000)).rejects.toThrow(); await expect(aliceRz.verifyNewDeviceOnExistingDevice(1000)).rejects.toThrow();
}); });
it("mismatched device key", async function () { it("mismatched device key", async function () {
@ -636,6 +636,6 @@ describe("Rendezvous", function () {
getFingerprint: () => "XXXX", getFingerprint: () => "XXXX",
}, },
}); });
expect(aliceRz.verifyNewDeviceOnExistingDevice(1000)).rejects.toThrow(/different key/); await expect(aliceRz.verifyNewDeviceOnExistingDevice(1000)).rejects.toThrow(/different key/);
}); });
}); });

View File

@ -95,10 +95,10 @@ describe("SimpleHttpRendezvousTransport", function () {
httpBackend.verifyNoOutstandingExpectation(); httpBackend.verifyNoOutstandingExpectation();
} }
} }
it("should throw an error when no server available", function () { it("should throw an error when no server available", async function () {
const client = makeMockClient({ userId: "@alice:example.com", deviceId: "DEVICEID", msc3886Enabled: false }); const client = makeMockClient({ userId: "@alice:example.com", deviceId: "DEVICEID", msc3886Enabled: false });
const simpleHttpTransport = new MSC3886SimpleHttpRendezvousTransport({ client, fetchFn }); const simpleHttpTransport = new MSC3886SimpleHttpRendezvousTransport({ client, fetchFn });
expect(simpleHttpTransport.send({})).rejects.toThrow("Invalid rendezvous URI"); await expect(simpleHttpTransport.send({})).rejects.toThrow("Invalid rendezvous URI");
}); });
it("POST to fallback server", async function () { it("POST to fallback server", async function () {
@ -130,7 +130,6 @@ describe("SimpleHttpRendezvousTransport", function () {
fetchFn, fetchFn,
}); });
const prom = simpleHttpTransport.send({}); const prom = simpleHttpTransport.send({});
expect(prom).rejects.toThrow();
httpBackend.when("POST", "https://fallbackserver/rz").response = { httpBackend.when("POST", "https://fallbackserver/rz").response = {
body: null, body: null,
response: { response: {
@ -138,7 +137,7 @@ describe("SimpleHttpRendezvousTransport", function () {
headers: {}, headers: {},
}, },
}; };
await httpBackend.flush(""); await Promise.all([expect(prom).rejects.toThrow(), httpBackend.flush("")]);
}); });
it("POST with absolute path response", async function () { it("POST with absolute path response", async function () {
@ -364,7 +363,7 @@ describe("SimpleHttpRendezvousTransport", function () {
fallbackRzServer: "https://fallbackserver/rz", fallbackRzServer: "https://fallbackserver/rz",
fetchFn, fetchFn,
}); });
expect(simpleHttpTransport.details()).rejects.toThrow(); await expect(simpleHttpTransport.details()).rejects.toThrow();
}); });
it("send after cancelled", async function () { it("send after cancelled", async function () {
@ -375,7 +374,7 @@ describe("SimpleHttpRendezvousTransport", function () {
fetchFn, fetchFn,
}); });
await simpleHttpTransport.cancel(RendezvousFailureReason.UserDeclined); await simpleHttpTransport.cancel(RendezvousFailureReason.UserDeclined);
expect(simpleHttpTransport.send({})).resolves.toBeUndefined(); await expect(simpleHttpTransport.send({})).resolves.toBeUndefined();
}); });
it("receive before ready", async function () { it("receive before ready", async function () {
@ -385,7 +384,7 @@ describe("SimpleHttpRendezvousTransport", function () {
fallbackRzServer: "https://fallbackserver/rz", fallbackRzServer: "https://fallbackserver/rz",
fetchFn, fetchFn,
}); });
expect(simpleHttpTransport.receive()).rejects.toThrow(); await expect(simpleHttpTransport.receive()).rejects.toThrow();
}); });
it("404 failure callback", async function () { it("404 failure callback", async function () {
@ -398,7 +397,6 @@ describe("SimpleHttpRendezvousTransport", function () {
onFailure, onFailure,
}); });
expect(simpleHttpTransport.send({ foo: "baa" })).resolves.toBeUndefined();
httpBackend.when("POST", "https://fallbackserver/rz").response = { httpBackend.when("POST", "https://fallbackserver/rz").response = {
body: null, body: null,
response: { response: {
@ -406,7 +404,10 @@ describe("SimpleHttpRendezvousTransport", function () {
headers: {}, headers: {},
}, },
}; };
await httpBackend.flush("", 1); await Promise.all([
expect(simpleHttpTransport.send({ foo: "baa" })).resolves.toBeUndefined(),
httpBackend.flush("", 1),
]);
expect(onFailure).toHaveBeenCalledWith(RendezvousFailureReason.Unknown); expect(onFailure).toHaveBeenCalledWith(RendezvousFailureReason.Unknown);
}); });
@ -438,7 +439,6 @@ describe("SimpleHttpRendezvousTransport", function () {
} }
{ {
// GET with 404 to simulate expiry // GET with 404 to simulate expiry
expect(simpleHttpTransport.receive()).resolves.toBeUndefined();
httpBackend.when("GET", "https://fallbackserver/rz/123").response = { httpBackend.when("GET", "https://fallbackserver/rz/123").response = {
body: { foo: "baa" }, body: { foo: "baa" },
response: { response: {
@ -446,7 +446,7 @@ describe("SimpleHttpRendezvousTransport", function () {
headers: {}, headers: {},
}, },
}; };
await httpBackend.flush(""); await Promise.all([expect(simpleHttpTransport.receive()).resolves.toBeUndefined(), httpBackend.flush("")]);
expect(onFailure).toHaveBeenCalledWith(RendezvousFailureReason.Expired); expect(onFailure).toHaveBeenCalledWith(RendezvousFailureReason.Expired);
} }
}); });

View File

@ -278,7 +278,7 @@ describe("IndexedDBStore", () => {
workerFactory: () => worker, workerFactory: () => worker,
}); });
await store.startup(); await store.startup();
await expect(store.destroy()).resolves; await store.destroy();
expect(terminate).toHaveBeenCalled(); expect(terminate).toHaveBeenCalled();
}); });
}); });

View File

@ -38,8 +38,6 @@ import { mkMessage } from "../test-utils/test-utils";
import { makeBeaconEvent } from "../test-utils/beacon"; import { makeBeaconEvent } from "../test-utils/beacon";
import { ReceiptType } from "../../src/@types/read_receipts"; import { ReceiptType } from "../../src/@types/read_receipts";
// TODO: Fix types throughout
describe("utils", function () { describe("utils", function () {
describe("encodeParams", function () { describe("encodeParams", function () {
it("should url encode and concat with &s", function () { it("should url encode and concat with &s", function () {

View File

@ -1607,7 +1607,7 @@ describe("Call", function () {
it("throws when there is no error listener", async () => { it("throws when there is no error listener", async () => {
call.off(CallEvent.Error, errorListener); call.off(CallEvent.Error, errorListener);
expect(call.placeVoiceCall()).rejects.toThrow(); await expect(call.placeVoiceCall()).rejects.toThrow();
}); });
describe("hasPeerConnection()", () => { describe("hasPeerConnection()", () => {