Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove expectThrowsAsync #277

Merged
merged 5 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 0 additions & 27 deletions packages/app-runtime/test/lib/TestUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,33 +135,6 @@ export class TestUtil {
}
}

public static async expectThrowsAsync(method: Function | Promise<any>, customExceptionMatcher: (e: Error) => void): Promise<void>;

public static async expectThrowsAsync(method: Function | Promise<any>, errorMessageRegexp: RegExp | string): Promise<void>;

public static async expectThrowsAsync(method: Function | Promise<any>, errorMessageRegexp: RegExp | string | ((e: Error) => void)): Promise<void> {
let error: Error | undefined;
try {
if (typeof method === "function") {
await method();
} else {
await method;
}
} catch (err: any) {
error = err;
}
expect(error).toBeInstanceOf(Error);

if (typeof errorMessageRegexp === "function") {
errorMessageRegexp(error!);
return;
}

if (errorMessageRegexp) {
expect(error!.message).toMatch(new RegExp(errorMessageRegexp));
}
}

public static async provideAccounts(runtime: AppRuntime, count: number): Promise<LocalAccountDTO[]> {
const accounts: LocalAccountDTO[] = [];

Expand Down
39 changes: 0 additions & 39 deletions packages/consumption/test/core/TestUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,45 +103,6 @@ export class TestUtil {
expect(error!.message).toMatch(new RegExp(errorMessageRegexp));
}

public static async expectThrowsAsync(method: Function | Promise<any>, customExceptionMatcher?: (e: Error) => void): Promise<void>;
public static async expectThrowsAsync(method: Function | Promise<any>, errorMessagePatternOrRegexp: RegExp): Promise<void>;
/**
*
* @param method The function which should throw the exception
* @param errorMessagePattern the pattern the error message should match (asterisks ('\*') are wildcards that correspond to '.\*' in regex)
*/
public static async expectThrowsAsync(method: Function | Promise<any>, errorMessagePattern: string): Promise<void>;

public static async expectThrowsAsync(method: Function | Promise<any>, errorMessageRegexp: RegExp | string | ((e: Error) => void) | undefined): Promise<void> {
let error: Error | undefined;
try {
if (typeof method === "function") {
await method();
} else {
await method;
}
} catch (err: unknown) {
if (!(err instanceof Error)) throw err;

error = err;
}

expect(error).toBeInstanceOf(Error);

if (!errorMessageRegexp) return;

if (typeof errorMessageRegexp === "function") {
errorMessageRegexp(error!);
return;
}

if (typeof errorMessageRegexp === "string") {
errorMessageRegexp = new RegExp(errorMessageRegexp.replaceAll("*", ".*"));
}

expect(error!.message).toMatch(new RegExp(errorMessageRegexp));
}

public static async createConnection(): Promise<IDatabaseConnection> {
let dbConnection;
if (process.env.USE_LOKIJS === "true") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2457,8 +2457,7 @@ describe("AttributesController", function () {
})
});

await TestUtil.expectThrowsAsync(
appConsumptionController.attributes.setAsDefaultRepositoryAttribute(sharedAttribute),
await expect(appConsumptionController.attributes.setAsDefaultRepositoryAttribute(sharedAttribute)).rejects.toThrow(
"error.consumption.attributes.isNotRepositoryAttribute"
);
});
Expand All @@ -2475,8 +2474,7 @@ describe("AttributesController", function () {
});
expect(repositoryAttribute.isDefault).toBeUndefined();

await TestUtil.expectThrowsAsync(
consumptionController.attributes.setAsDefaultRepositoryAttribute(repositoryAttribute),
await expect(consumptionController.attributes.setAsDefaultRepositoryAttribute(repositoryAttribute)).rejects.toThrow(
"error.consumption.attributes.setDefaultRepositoryAttributesIsDisabled"
);
});
Expand Down Expand Up @@ -2864,7 +2862,7 @@ describe("AttributesController", function () {
});

test("should throw if an unassigned attribute id is queried", async function () {
await TestUtil.expectThrowsAsync(consumptionController.attributes.getVersionsOfAttribute(CoreId.from("ATTxxxxxxxxxxxxxxxxx")), "error.transport.recordNotFound");
await expect(consumptionController.attributes.getVersionsOfAttribute(CoreId.from("ATTxxxxxxxxxxxxxxxxx"))).rejects.toThrow("error.transport.recordNotFound");
});

test("should check if two attributes are subsequent in succession", async function () {
Expand Down Expand Up @@ -3052,7 +3050,7 @@ describe("AttributesController", function () {
});

test("should throw if an unassigned attribute id is queried", async function () {
await TestUtil.expectThrowsAsync(consumptionController.attributes.getSharedVersionsOfAttribute(CoreId.from("ATTxxxxxxxxxxxxxxxxx")), "error.transport.recordNotFound");
await expect(consumptionController.attributes.getSharedVersionsOfAttribute(CoreId.from("ATTxxxxxxxxxxxxxxxxx"))).rejects.toThrow("error.transport.recordNotFound");
});

test("should return an empty list if a shared identity attribute is queried", async function () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1171,13 +1171,12 @@ export class RequestsThen {
}

public async itThrowsAnErrorWithTheErrorMessage(errorMessage: string): Promise<void> {
await TestUtil.expectThrowsAsync(this.context.actionToTry!, errorMessage);
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));
await expect(this.context.actionToTry!).rejects.toThrow(regex);
}

public async itThrowsAnErrorWithTheErrorCode(code: string): Promise<void> {
await TestUtil.expectThrowsAsync(this.context.actionToTry!, (error: Error) => {
expect((error as any).code).toStrictEqual(code);
});
await expect(this.context.actionToTry!).rejects.toThrow(code);
}

public eventHasBeenPublished<TEvent extends DataEvent<unknown>>(
Expand Down
22 changes: 15 additions & 7 deletions packages/content/test/requests/Request.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Serializable, type } from "@js-soft/ts-serval";
import { CoreDate, CoreId } from "@nmshd/core-types";
import { IRequest, IRequestItem, IRequestItemGroup, Request, RequestItem, RequestItemGroup, RequestItemGroupJSON, RequestItemJSON, RequestJSON } from "../../src";
import { expectThrowsAsync } from "../testUtils";

interface TestRequestItemJSON extends RequestItemJSON {
"@type": "TestRequestItem";
Expand Down Expand Up @@ -127,16 +126,19 @@ describe("Request", function () {
expect(serializedRequest).toStrictEqual(requestJSON);
});

test("must have at least one item", async function () {
test("must have at least one item", function () {
const requestJSON = {
"@type": "Request",
items: []
} as RequestJSON;

await expectThrowsAsync(() => Request.from(requestJSON), "*Request.items*may not be empty");
const errorMessage = "*Request.items*may not be empty";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Request.from(requestJSON)).toThrow(regex);
});

test("groups must have at least one item", async function () {
test("groups must have at least one item", function () {
const requestJSON = {
"@type": "Request",
id: "CNSREQ1",
Expand All @@ -149,10 +151,13 @@ describe("Request", function () {
]
} as RequestJSON;

await expectThrowsAsync(() => Request.from(requestJSON), "*RequestItemGroup.items*may not be empty*");
const errorMessage = "*RequestItemGroup.items*may not be empty*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Request.from(requestJSON)).toThrow(regex);
});

test("mustBeAccepted is mandatory", async function () {
test("mustBeAccepted is mandatory", function () {
const requestJSON = {
"@type": "Request",
items: [
Expand All @@ -162,6 +167,9 @@ describe("Request", function () {
]
} as RequestJSON;

await expectThrowsAsync(() => Serializable.fromUnknown(requestJSON), "TestRequestItem.mustBeAccepted*Value is not defined");
const errorMessage = "TestRequestItem.mustBeAccepted*Value is not defined";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Serializable.fromUnknown(requestJSON)).toThrow(regex);
});
});
43 changes: 30 additions & 13 deletions packages/content/test/requests/Response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
ResponseJSON,
ResponseResult
} from "../../src";
import { expectThrowsAsync } from "../testUtils";

interface ITestAcceptResponseItem extends IAcceptResponseItem {
test: string;
Expand Down Expand Up @@ -141,18 +140,21 @@ describe("Response", function () {
expect(serializedRequest).toStrictEqual(responseJSON);
});

test("must have at least one item", async function () {
test("must have at least one item", function () {
const responseJSON = {
"@type": "Response",
result: ResponseResult.Accepted,
requestId: "CNSREQ1",
items: []
} as ResponseJSON;

await expectThrowsAsync(() => Response.from(responseJSON), "*Response.items*may not be empty*");
const errorMessage = "*Response.items*may not be empty*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Response.from(responseJSON)).toThrow(regex);
});

test("groups must have at least one item", async function () {
test("groups must have at least one item", function () {
const responseJSON = {
"@type": "Response",
result: ResponseResult.Accepted,
Expand All @@ -165,7 +167,10 @@ describe("Response", function () {
]
} as ResponseJSON;

await expectThrowsAsync(() => Response.from(responseJSON), "*ResponseItemGroup.items*may not be empty*");
const errorMessage = "*ResponseItemGroup.items*may not be empty*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Response.from(responseJSON)).toThrow(regex);
});

test("allows an inherited AcceptResponseItem in the items", function () {
Expand Down Expand Up @@ -196,7 +201,7 @@ describe("Response", function () {
});

describe("Throws an error when a mandatory property is missing", function () {
test("throws on missing requestId", async function () {
test("throws on missing requestId", function () {
const responseJSON = {
"@type": "Response",
result: ResponseResult.Accepted,
Expand All @@ -208,10 +213,13 @@ describe("Response", function () {
]
} as ResponseJSON;

await expectThrowsAsync(() => Response.from(responseJSON), "*Response.requestId*Value is not defined*");
const errorMessage = "*Response.requestId*Value is not defined*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Response.from(responseJSON)).toThrow(regex);
});

test("throws on missing response item status", async function () {
test("throws on missing response item status", function () {
const responseJSON = {
"@type": "Response",
result: ResponseResult.Accepted,
Expand All @@ -223,10 +231,13 @@ describe("Response", function () {
]
} as ResponseJSON;

await expectThrowsAsync(() => Response.from(responseJSON), "*ResponseItem.result*Value is not defined*");
const errorMessage = "*ResponseItem.result*Value is not defined*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Response.from(responseJSON)).toThrow(regex);
});

test("throws on missing error response content properties", async function () {
test("throws on missing error response content properties", function () {
const jsonWithMissingErrorCode = {
"@type": "Response",
result: ResponseResult.Accepted,
Expand All @@ -240,10 +251,13 @@ describe("Response", function () {
]
} as ResponseJSON;

await expectThrowsAsync(() => Response.from(jsonWithMissingErrorCode), "*ErrorResponseItem.code*Value is not defined*");
const errorMessage = "*ErrorResponseItem.code*Value is not defined*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Response.from(jsonWithMissingErrorCode)).toThrow(regex);
});

test("error response content message is mandatory", async function () {
test("error response content message is mandatory", function () {
const jsonWithMissingErrorCode: ResponseJSON = {
"@type": "Response",
result: ResponseResult.Accepted,
Expand All @@ -257,7 +271,10 @@ describe("Response", function () {
]
};

await expectThrowsAsync(() => Response.from(jsonWithMissingErrorCode), "*ErrorResponseItem.message*Value is not defined*");
const errorMessage = "*ErrorResponseItem.message*Value is not defined*";
const regex = new RegExp(errorMessage.replace(/\*/g, ".*"));

expect(() => Response.from(jsonWithMissingErrorCode)).toThrow(regex);
});
});
});
41 changes: 0 additions & 41 deletions packages/content/test/testUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,44 +16,3 @@ export function expectThrows(method: Function, errorMessage = ""): void {
expect(error!.message, `Error Message: ${error!.message}`).toMatch(new RegExp(`^${errorMessage}`));
}
}

export async function expectThrowsAsync(method: Function | Promise<any>, customExceptionMatcher?: (e: Error) => void): Promise<void>;

export async function expectThrowsAsync(method: Function | Promise<any>, errorMessagePatternOrRegexp: RegExp): Promise<void>;

/**
*
* @param method The function which should throw the exception
* @param errorMessagePattern the pattern the error message should match (asterisks ('\*') are wildcards that correspond to '.\*' in regex)
*/
export async function expectThrowsAsync(method: Function | Promise<any>, errorMessagePattern: string): Promise<void>;

export async function expectThrowsAsync(method: Function | Promise<any>, errorMessageRegexp: RegExp | string | ((e: Error) => void) | undefined): Promise<void> {
let error: Error | undefined;
try {
if (typeof method === "function") {
await method();
} else {
await method;
}
} catch (err: unknown) {
if (!(err instanceof Error)) throw err;

error = err;
}

expect(error, "Expected an error to be thrown").toBeInstanceOf(Error);

if (!errorMessageRegexp) return;

if (typeof errorMessageRegexp === "function") {
errorMessageRegexp(error!);
return;
}

if (typeof errorMessageRegexp === "string") {
errorMessageRegexp = new RegExp(errorMessageRegexp.replaceAll("*", ".*"));
}

expect(error!.message).toMatch(new RegExp(errorMessageRegexp));
}
Original file line number Diff line number Diff line change
Expand Up @@ -169,8 +169,8 @@ describe("Device Onboarding", function () {
test("should have changed the password of the created device (backbone)", async function () {
TestUtil.useFatalLoggerFactory();

await TestUtil.expectThrowsAsync(async () => {
await expect(async () => {
await deviceTest.onboardDevice(sharedSecret);
}, "error.transport.request.noAuthGrant");
}).rejects.toThrow("error.transport.request.noAuthGrant");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,13 @@ describe("RelationshipTemplateController", function () {
});

test("should throw an error with maxNumberOfAllocations=0", async function () {
await TestUtil.expectThrowsAsync(async () => {
await expect(async () => {
await sender.relationshipTemplates.sendRelationshipTemplate({
content: { a: "A" },
expiresAt: CoreDate.utc().add({ minutes: 1 }),
maxNumberOfAllocations: 0
});
}, /SendRelationshipTemplateParameters.maxNumberOfAllocations/);
}).rejects.toThrow(/SendRelationshipTemplateParameters.maxNumberOfAllocations/);
});

test("should send and receive a RelationshipTemplate using a RelationshipTemplateReference", async function () {
Expand Down
Loading