Skip to content

Commit

Permalink
test: fix type checks in unit tests (#6071)
Browse files Browse the repository at this point in the history
  • Loading branch information
trivikr committed May 7, 2024
1 parent 246fced commit 809b7b5
Show file tree
Hide file tree
Showing 25 changed files with 62 additions and 48 deletions.
Expand Up @@ -4,7 +4,9 @@ import { KeyNodeChildren } from "../commands/utils";
import { DynamoDBDocumentClientCommand } from "./DynamoDBDocumentClientCommand";

class AnyCommand extends DynamoDBDocumentClientCommand<{}, {}, {}, {}, {}> {
// @ts-ignore Property 'middlewareStack' has no initializer
public middlewareStack: MiddlewareStack<{}, {}>;
// @ts-ignore Property 'input' has no initializer
public input: {};
protected inputKeyNodes: KeyNodeChildren = {};
protected outputKeyNodes: KeyNodeChildren = {};
Expand All @@ -14,7 +16,7 @@ class AnyCommand extends DynamoDBDocumentClientCommand<{}, {}, {}, {}, {}> {
protected readonly clientCommand = {
middlewareStack: {
argCaptor: this.argCaptor,
addRelativeTo(fn, config) {
addRelativeTo(fn: any, config: any) {
this.argCaptor.push([fn, config]);
},
},
Expand Down
8 changes: 4 additions & 4 deletions packages/cloudfront-signer/src/sign.spec.ts
Expand Up @@ -131,7 +131,7 @@ describe("getSignedUrl", () => {
expect(result).toBe(`${url}?Expires=${epochDateLessThan}&Key-Pair-Id=${keyPairId}&Signature=${signature}`);
const parsedUrl = parseUrl(result);
expect(parsedUrl).toBeDefined();
const signatureQueryParam = denormalizeBase64(parsedUrl.query["Signature"] as string);
const signatureQueryParam = denormalizeBase64(parsedUrl.query!["Signature"] as string);
expect(verifySignature(signatureQueryParam, policyStr)).toBeTruthy();
});
it("should sign a URL with a custom policy containing a start date", () => {
Expand Down Expand Up @@ -162,7 +162,7 @@ describe("getSignedUrl", () => {
expect(result).toBe(`${url}?Policy=${encodeToBase64(policyStr)}&Key-Pair-Id=${keyPairId}&Signature=${signature}`);
const parsedUrl = parseUrl(result);
expect(parsedUrl).toBeDefined();
const signatureQueryParam = denormalizeBase64(parsedUrl.query["Signature"] as string);
const signatureQueryParam = denormalizeBase64(parsedUrl.query!["Signature"] as string);
expect(verifySignature(signatureQueryParam, policyStr)).toBeTruthy();
});
it("should sign a URL with a custom policy containing an ip address", () => {
Expand Down Expand Up @@ -193,7 +193,7 @@ describe("getSignedUrl", () => {
expect(result).toBe(`${url}?Policy=${encodeToBase64(policyStr)}&Key-Pair-Id=${keyPairId}&Signature=${signature}`);
const parsedUrl = parseUrl(result);
expect(parsedUrl).toBeDefined();
const signatureQueryParam = denormalizeBase64(parsedUrl.query["Signature"] as string);
const signatureQueryParam = denormalizeBase64(parsedUrl.query!["Signature"] as string);
expect(verifySignature(signatureQueryParam, policyStr)).toBeTruthy();
});
it("should sign a URL with a custom policy containing a start date and ip address", () => {
Expand Down Expand Up @@ -228,7 +228,7 @@ describe("getSignedUrl", () => {
expect(result).toBe(`${url}?Policy=${encodeToBase64(policyStr)}&Key-Pair-Id=${keyPairId}&Signature=${signature}`);
const parsedUrl = parseUrl(result);
expect(parsedUrl).toBeDefined();
const signatureQueryParam = denormalizeBase64(parsedUrl.query["Signature"] as string);
const signatureQueryParam = denormalizeBase64(parsedUrl.query!["Signature"] as string);
expect(verifySignature(signatureQueryParam, policyStr)).toBeTruthy();
});
it("should allow an ip address with and without a mask", () => {
Expand Down
@@ -1,5 +1,5 @@
describe("emitWarningIfUnsupportedVersion", () => {
let emitWarningIfUnsupportedVersion;
let emitWarningIfUnsupportedVersion: any;
const emitWarning = process.emitWarning;
const supportedVersion = "16.0.0";

Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/protocols/xml/parseXmlBody.spec.ts
Expand Up @@ -43,7 +43,7 @@ describe(parseXmlBody.name, () => {
<ID>string</ID>
</Owner>
`);
const parsed = await parseXmlBody(xml, context as any as SerdeContext).catch((_) => _);
const parsed = await parseXmlBody(xml, context as any as SerdeContext).catch((_: any) => _);
expect(parsed.toString()).toEqual(`Error: Unclosed tag 'ListAllMyBucketsResult'.:2:1`);
});

Expand All @@ -54,7 +54,7 @@ describe(parseXmlBody.name, () => {
<Bucket>
<CreationDate>timestamp</Creatio
`);
const parsed = await parseXmlBody(xml, context as any as SerdeContext).catch((_) => _);
const parsed = await parseXmlBody(xml, context as any as SerdeContext).catch((_: any) => _);
expect(parsed.toString()).toEqual(`Error: Closing tag 'Creatio' doesn't have proper closing.:6:1`);
});
});
Expand Up @@ -110,7 +110,7 @@ describe(resolveAssumeRoleCredentials.name, () => {
duration_seconds: "2000",
});

const getMockProfilesWithCredSource = (additionalData) => ({
const getMockProfilesWithCredSource = (additionalData: any) => ({
[mockProfileName]: {
credential_source: mockCredentialSource,
...additionalData,
Expand Down
Expand Up @@ -18,7 +18,7 @@ describe(getValidatedProcessCredentials.name, () => {
Expiration: mockExpiration,
});

it.each([undefined, 2])("throws Error when Version is %s", (Version) => {
it.each([2])("throws Error when Version is %s", (Version) => {
expect(() => {
getValidatedProcessCredentials(mockProfileName, {
...getMockProcessCreds(),
Expand Down
Expand Up @@ -20,6 +20,7 @@ describe(validateSsoProfile.name, () => {
"throws if '%s' is missing from profile",
(key) => {
const profileToVerify = getMockSsoProfile();
// @ts-ignore Element implicitly has an 'any' type
delete profileToVerify[key];

expect(() => {
Expand All @@ -38,6 +39,7 @@ describe(validateSsoProfile.name, () => {

it.each(["sso_session"])("does not throw if '%s' is missing from profile", (key) => {
const profileToVerify = getMockSsoProfile();
// @ts-ignore Element implicitly has an 'any' type
delete profileToVerify[key];

expect(() => {
Expand Down
2 changes: 1 addition & 1 deletion packages/endpoint-cache/src/EndpointCache.spec.ts
Expand Up @@ -6,7 +6,7 @@ import { EndpointCache } from "./EndpointCache";
jest.mock("mnemonist/lru-cache");

describe(EndpointCache.name, () => {
let endpointCache;
let endpointCache: EndpointCache;
const capacity = 100;
const key = "key";

Expand Down
Expand Up @@ -10,7 +10,7 @@ describe("NODE_ENDPOINT_DISCOVERY_CONFIG_OPTIONS", () => {
describe("environmentVariableSelector", () => {
const ENV_ENDPOINT_DISCOVERY = ["AWS_ENABLE_ENDPOINT_DISCOVERY", "AWS_ENDPOINT_DISCOVERY_ENABLED"];
describe.each(ENV_ENDPOINT_DISCOVERY)("env key: %p", (envKey) => {
const envValues = {};
const envValues: Record<string, string | undefined> = {};

beforeEach(() => {
ENV_ENDPOINT_DISCOVERY.forEach((envKey) => {
Expand Down
Expand Up @@ -10,8 +10,8 @@ describe(getChecksumAlgorithmForRequest.name, () => {
expect(getChecksumAlgorithmForRequest({}, { requestChecksumRequired: true })).toEqual(ChecksumAlgorithm.MD5);
});

it.each([false, undefined])("returns undefined if requestChecksumRequired=%s", (requestChecksumRequired) => {
expect(getChecksumAlgorithmForRequest({}, { requestChecksumRequired })).toBeUndefined();
it("returns undefined if requestChecksumRequired is false", () => {
expect(getChecksumAlgorithmForRequest({}, { requestChecksumRequired: false })).toBeUndefined();
});
});

Expand All @@ -24,8 +24,8 @@ describe(getChecksumAlgorithmForRequest.name, () => {
);
});

it.each([false, undefined])("returns undefined if requestChecksumRequired=%s", (requestChecksumRequired) => {
expect(getChecksumAlgorithmForRequest({}, { ...mockOptions, requestChecksumRequired })).toBeUndefined();
it("returns undefined if requestChecksumRequired is false", () => {
expect(getChecksumAlgorithmForRequest({}, { ...mockOptions, requestChecksumRequired: false })).toBeUndefined();
});
});

Expand Down
Expand Up @@ -63,7 +63,7 @@ describe(validateChecksumFromResponse.name, () => {
});

it("if response algorithms is empty", async () => {
const emptyAlgorithmsList = [];
const emptyAlgorithmsList: string[] = [];
await validateChecksumFromResponse(mockResponse, { ...mockOptions, responseAlgorithms: emptyAlgorithmsList });
expect(getChecksumAlgorithmListForResponse).toHaveBeenCalledWith(emptyAlgorithmsList);
expect(getChecksumLocationName).not.toHaveBeenCalled();
Expand Down
2 changes: 1 addition & 1 deletion packages/middleware-sdk-ec2/src/index.spec.ts
Expand Up @@ -10,7 +10,7 @@ const handler = copySnapshotPresignedUrlMiddleware({
region,
sha256: MockSha256,
signingEscapePath: true,
endpointProvider: async (...args) =>
endpointProvider: async () =>
({
url: {
hostname: "ec2.src-region.test-host.com",
Expand Down
Expand Up @@ -5,7 +5,7 @@ import { checkContentLengthHeader } from "./check-content-length-header";
describe("checkContentLengthHeaderMiddleware", () => {
const mockNextHandler = jest.fn();

let spy;
let spy: jest.SpyInstance;

beforeEach(() => {
spy = jest.spyOn(console, "warn");
Expand Down Expand Up @@ -80,7 +80,7 @@ describe("checkContentLengthHeaderMiddleware", () => {
logger: {
called: false,
calledWith: "",
warn(msg) {
warn(msg: string) {
this.called = true;
this.calledWith = msg;
},
Expand Down
16 changes: 10 additions & 6 deletions packages/middleware-signing/src/awsAuthMiddleware.spec.ts
@@ -1,6 +1,7 @@
import { HttpRequest } from "@smithy/protocol-http";
import { RequestSigner } from "@smithy/types";
import { FinalizeHandler, RequestSigner } from "@smithy/types";

import { AwsAuthResolvedConfig } from "./awsAuthConfiguration";
import { awsAuthMiddleware } from "./awsAuthMiddleware";
import { getSkewCorrectedDate } from "./utils/getSkewCorrectedDate";
import { getUpdatedSystemClockOffset } from "./utils/getUpdatedSystemClockOffset";
Expand All @@ -11,9 +12,9 @@ jest.mock("./utils/getSkewCorrectedDate");
describe(awsAuthMiddleware.name, () => {
let mockSignFn: jest.Mock<any, any>;
let mockSigner: () => Promise<RequestSigner>;
let mockNext;
let mockOptions;
let mockOptions: AwsAuthResolvedConfig;

const mockNext: jest.MockedFunction<FinalizeHandler<any, any>> = jest.fn();
const mockSystemClockOffset = 100;
const mockUpdatedSystemClockOffset = 500;
const mockSigningHandlerArgs = {
Expand All @@ -24,12 +25,12 @@ describe(awsAuthMiddleware.name, () => {
};
const mockSignedRequest = new HttpRequest({ headers: { signed: "true" } });
const mockSkewCorrectedDate = new Date();
const mockResponse = { response: "" };
const mockResponse = { output: "", response: "" };

beforeEach(() => {
mockSignFn = jest.fn().mockResolvedValue(mockSignedRequest);
mockSigner = () => Promise.resolve({ sign: mockSignFn } as RequestSigner);
mockNext = jest.fn().mockResolvedValue(mockResponse);
mockNext.mockResolvedValue(mockResponse);
mockOptions = {
credentials: jest.fn(),
signer: mockSigner,
Expand Down Expand Up @@ -78,7 +79,10 @@ describe(awsAuthMiddleware.name, () => {
const options = { ...mockOptions };
const signingHandler = awsAuthMiddleware(options)(mockNext, {});

const mockResponseWithDateHeader = { response: { headers: { [headerName]: dateHeader }, statusCode: 200 } };
const mockResponseWithDateHeader = {
output: "",
response: { headers: { [headerName]: dateHeader }, statusCode: 200 },
};
mockNext.mockResolvedValue(mockResponseWithDateHeader);

const output = await signingHandler(mockSigningHandlerArgs);
Expand Down
2 changes: 1 addition & 1 deletion packages/middleware-token/src/resolveTokenConfig.spec.ts
Expand Up @@ -29,7 +29,7 @@ describe(resolveTokenConfig.name, () => {
expect(tokenDefaultProvider).not.toHaveBeenCalled();
});

const testTokenProviderWithToken = (token) => {
const testTokenProviderWithToken = (token: any) => {
expect(resolveTokenConfig({ ...mockInput, token })).toEqual({ ...mockInput, token: mockOutputToken });
expect(normalizeTokenProvider).toHaveBeenCalledWith(token);
};
Expand Down
Expand Up @@ -153,7 +153,7 @@ describe(EventStreamPayloadHandler.name, () => {
const chunks: any = [];
const reader = handledRequest.body.getReader();
const push = () => {
reader.read().then(({ done, value }) => {
reader.read().then(({ done, value }: { done: any; value: any }) => {
if (!done) {
chunks.push(value);
push();
Expand Down
Expand Up @@ -10,6 +10,7 @@ describe(isFipsRegion.name, () => {
});

it.each([undefined, null])("returns false for %s", (input) => {
// @ts-ignore Argument of type 'null | undefined' is not assignable to parameter of type 'string'.
expect(isFipsRegion(input)).toEqual(false);
});
});
@@ -1,3 +1,5 @@
import { Provider } from "@smithy/types";

import { getRealRegion } from "./getRealRegion";
import { isFipsRegion } from "./isFipsRegion";
import { resolveRegionConfig } from "./resolveRegionConfig";
Expand Down Expand Up @@ -45,8 +47,8 @@ describe("RegionConfig", () => {
});

describe("useFipsEndpoint", () => {
let mockRegionProvider;
let mockUseFipsEndpoint;
let mockRegionProvider: string | Provider<string>;
let mockUseFipsEndpoint: boolean | Provider<boolean>;

beforeEach(() => {
mockRegionProvider = jest.fn().mockResolvedValueOnce(Promise.resolve(mockRegion));
Expand Down
3 changes: 2 additions & 1 deletion packages/s3-request-presigner/src/getSignedUrl.spec.ts
Expand Up @@ -23,6 +23,7 @@ jest.mock("@aws-sdk/util-format-url", () => ({
formatUrl: (url: any) => url,
}));

import { HttpRequest } from "@smithy/protocol-http";
import { RequestPresigningArguments } from "@smithy/types";

import { getSignedUrl } from "./getSignedUrl";
Expand Down Expand Up @@ -145,7 +146,7 @@ describe("getSignedUrl", () => {
});
command.middlewareStack.add(
(next) => (args) => {
(args.request ?? {})[header] = "foo";
(args.request as HttpRequest).headers[header] = "foo";
return next(args);
},
{ step: "serialize", priority: "low" }
Expand Down
10 changes: 6 additions & 4 deletions packages/token-providers/src/fromSso.spec.ts
Expand Up @@ -141,6 +141,7 @@ describe(fromSso.name, () => {
expect(validateTokenKey).toHaveBeenNthCalledWith(
(validateTokenKey as jest.Mock).mock.calls.length,
key,
// @ts-ignore Element implicitly has an 'any' type
mockSsoToken[key]
);
});
Expand Down Expand Up @@ -215,32 +216,33 @@ describe(fromSso.name, () => {
expect(validateTokenKey).toHaveBeenNthCalledWith(
(validateTokenKey as jest.Mock).mock.calls.length,
key,
// @ts-ignore Element implicitly has an 'any' type
mockSsoToken[key],
true
);
}
);

describe("failure wrt token from ssoOidc.createToken()", () => {
const returnExistingValidTokenInExpiryWindowTest = async (fromSso) => {
const returnExistingValidTokenInExpiryWindowTest = async (fromSsoImpl: typeof fromSso) => {
const mockValidSsoTokenInExpiryWindow = {
...mockSsoToken,
expiresAt: new Date(mockDateNow + EXPIRE_WINDOW_MS - 1000).toISOString(),
};
(getSSOTokenFromFile as jest.Mock).mockResolvedValueOnce(mockValidSsoTokenInExpiryWindow);
await expect(fromSso(mockInit)()).resolves.toStrictEqual({
await expect(fromSsoImpl(mockInit)()).resolves.toStrictEqual({
token: mockValidSsoTokenInExpiryWindow.accessToken,
expiration: new Date(mockValidSsoTokenInExpiryWindow.expiresAt),
});
expect(getNewSsoOidcToken).toHaveBeenCalledWith(mockValidSsoTokenInExpiryWindow, mockSsoSession.sso_region);
};

const throwErrorExpiredTokenTest = async (fromSso) => {
const throwErrorExpiredTokenTest = async (fromSsoImpl: typeof fromSso) => {
const ssoTokenExpiryError = new TokenProviderError(`SSO Token is expired. ${REFRESH_MESSAGE}`, false);
(validateTokenExpiry as jest.Mock).mockImplementation(() => {
throw ssoTokenExpiryError;
});
await expect(fromSso(mockInit)()).rejects.toStrictEqual(ssoTokenExpiryError);
await expect(fromSsoImpl(mockInit)()).rejects.toStrictEqual(ssoTokenExpiryError);
expect(getNewSsoOidcToken).toHaveBeenCalledWith(mockSsoToken, mockSsoSession.sso_region);
};

Expand Down
2 changes: 1 addition & 1 deletion packages/token-providers/src/getNewSsoOidcToken.spec.ts
Expand Up @@ -7,7 +7,7 @@ jest.mock("@aws-sdk/client-sso-oidc");
jest.mock("./getSsoOidcClient");

describe(getNewSsoOidcToken.name, () => {
let mockSend;
let mockSend: any;

const mockSsoRegion = "mockSsoRegion";
const mockSsoToken = {
Expand Down
2 changes: 1 addition & 1 deletion packages/token-providers/src/getSsoOidcClient.spec.ts
Expand Up @@ -4,7 +4,7 @@ jest.mock("@aws-sdk/client-sso-oidc");

describe("getSsoOidcClient", () => {
const mockSsoRegion = "mockSsoRegion";
const getMockClient = (region) => ({ region });
const getMockClient = (region: string) => ({ region });

beforeEach(() => {
(SSOOIDCClient as jest.Mock).mockImplementation(({ region }) => getMockClient(region));
Expand Down
12 changes: 6 additions & 6 deletions packages/util-dynamodb/src/convertToNative.spec.ts
Expand Up @@ -216,14 +216,14 @@ describe("convertToNative", () => {
});

it(`testing map with big objects`, () => {
const input = Array.from({ length: 100000 }, (_, idx) => [idx, { N: "1.00" }]).reduce((acc, [key, value]) => {
acc[key as unknown as string] = value;
const input = Array.from(Array(100000).keys()).reduce((acc, index) => {
acc[index] = { N: "1.00" };
return acc;
}, {});
const output = Array.from({ length: 100000 }, (_, idx) => [idx, 1]).reduce((acc, [key, value]) => {
acc[key as unknown as string] = value;
}, {} as Record<string, any>);
const output = Array.from(Array(100000).keys()).reduce((acc, index) => {
acc[index] = 1;
return acc;
}, {});
}, {} as Record<string, number>);
expect(convertToNative({ M: input })).toEqual(output);
});
});
Expand Down
2 changes: 1 addition & 1 deletion packages/util-endpoints/src/lib/aws/partition.spec.ts
Expand Up @@ -110,7 +110,7 @@ describe("partition", () => {

useDefaultPartitionInfo();
// result is matched by regex, but customization is no longer present.
expect(partition(testRegion)["description"]).not.toBeDefined();
expect((partition(testRegion) as any)["description"]).not.toBeDefined();
});

it("should optionally set a user agent prefix", async () => {
Expand Down

0 comments on commit 809b7b5

Please sign in to comment.