Skip to content

test: run tests with vitest, fix test type errors #1602

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

Merged
merged 2 commits into from
May 22, 2025
Merged
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
2 changes: 2 additions & 0 deletions .changeset/rare-dancers-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -18,6 +18,21 @@ generate-protocol-tests:
test-protocols:
(cd ./private/smithy-rpcv2-cbor && npx vitest run --globals)

test-unit:
yarn g:vitest run -c vitest.config.ts

test-browser:
yarn g:vitest run -c vitest.config.browser.ts

# typecheck for test code.
test-types:
npx tsc -p tsconfig.test.json

test-integration:
make test-browser
yarn g:vitest run -c vitest.config.integ.ts
make test-types

turbo-clean:
@read -p "Are you sure you want to delete your local cache? [y/N]: " ans && [ $${ans:-N} = y ]
@echo "\nDeleted cache folders: \n--------"
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -7,8 +7,8 @@
"scripts": {
"clean": "turbo run clean --force --parallel",
"build": "turbo run build",
"test": "turbo run test",
"test:integration": "yarn build-test-packages && turbo run test:integration",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as with jsv3, turbo is a slow way to run tests because it spins up separate vite processes.

A singular vitest process with a view of all tests is much faster for test compilation.

"test": "make test-unit",
"test:integration": "yarn build-test-packages && make test-integration",
"test:protocols": "make generate-protocol-tests test-protocols",
"lint": "turbo run lint",
"lint-fix": "turbo run lint -- --fix",
Original file line number Diff line number Diff line change
@@ -12,6 +12,6 @@ describe(isFipsRegion.name, () => {
});

it.each([undefined, null])("returns false for %s", (input) => {
expect(isFipsRegion(input)).toEqual(false);
expect(isFipsRegion(input as any)).toEqual(false);
});
});
Original file line number Diff line number Diff line change
@@ -54,8 +54,8 @@ describe("RegionConfig", () => {
});

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

beforeEach(() => {
mockRegionProvider = vi.fn().mockResolvedValueOnce(Promise.resolve(mockRegion));
Original file line number Diff line number Diff line change
@@ -56,9 +56,9 @@ describe(getRegionInfo.name, () => {
const getMockResolvedRegion = (regionCase: RegionCase): string =>
regionCase !== RegionCase.ENDPOINT ? mockRegion : mockEndpointRegion;

const getMockResolvedPartitionOptions = (partitionHash) => ({ partitionHash });
const getMockResolvedPartitionOptions = (partitionHash: PartitionHash) => ({ partitionHash });

const getMockRegionInfoOptions = (regionHash, getResolvedPartitionOptions) => ({
const getMockRegionInfoOptions = (regionHash: RegionHash, getResolvedPartitionOptions: any) => ({
...getResolvedPartitionOptions,
signingService: mockSigningService,
regionHash,
Original file line number Diff line number Diff line change
@@ -32,6 +32,6 @@ describe(getResolvedPartition.name, () => {
});

it("returns aws if partitionHash is empty", () => {
expect(getResolvedPartition(mockRegion, { partitionHash: undefined })).toBe("aws");
expect(getResolvedPartition(mockRegion, { partitionHash: undefined as any })).toBe("aws");
});
});
3 changes: 2 additions & 1 deletion packages/core/src/submodules/cbor/cbor.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as fs from "fs";
// @ts-ignore
import JSONbig from "json-bigint";
import * as path from "path";
import { describe, expect, test as it } from "vitest";
@@ -290,7 +291,7 @@ describe("cbor", () => {
return scalar * sum * exponentScalar;
}

function translateTestData(data: any) {
function translateTestData(data: any): any {
const [type, value] = Object.entries(data)[0] as [string, any];
switch (type) {
case "null":
Original file line number Diff line number Diff line change
@@ -85,7 +85,7 @@ describe(schemaDeserializationMiddleware.name, () => {
expect(mockNext).toHaveBeenCalledWith(mockArgs);
expect(mockDeserializer).toHaveBeenCalledTimes(1);
expect(mockDeserializer).toHaveBeenCalledWith(
undefined as SchemaRef,
undefined as any as SchemaRef,
{
...mockOptions,
__smithy_context: {},
Original file line number Diff line number Diff line change
@@ -59,7 +59,7 @@ describe(schemaSerializationMiddleware.name, () => {
await expect(schemaSerializationMiddleware(mockOptions)(mockNext, {})(mockArgs)).resolves.toStrictEqual(mockReturn);

expect(mockSerializer).toHaveBeenCalledTimes(1);
expect(mockSerializer).toHaveBeenCalledWith(undefined as SchemaRef, mockArgs.input, {
expect(mockSerializer).toHaveBeenCalledWith(undefined as unknown as SchemaRef, mockArgs.input, {
...mockOptions,
__smithy_context: {},
});
Original file line number Diff line number Diff line change
@@ -20,7 +20,6 @@ import EventEmitter from "events";
import { request } from "http";

describe("httpRequest", () => {
let port: number;
const hostname = "localhost";
const path = "/";

@@ -53,7 +52,7 @@ describe("httpRequest", () => {

mockResponse({ expectedResponse });

const response = await httpRequest({ hostname, path, port });
const response = await httpRequest({ hostname, path });
expect(response.toString()).toStrictEqual(expectedResponse);
});

@@ -62,7 +61,7 @@ describe("httpRequest", () => {
const expectedResponse = "expectedResponse";
mockResponse({ expectedResponse });

const response = await httpRequest({ hostname, path, port, method });
const response = await httpRequest({ hostname, path, method });
expect(response.toString()).toStrictEqual(expectedResponse);
});

@@ -71,7 +70,7 @@ describe("httpRequest", () => {
const encapsulatedIPv6Hostname = "[::1]";
mockResponse({ expectedResponse });

const response = await httpRequest({ hostname: encapsulatedIPv6Hostname, path, port });
const response = await httpRequest({ hostname: encapsulatedIPv6Hostname, path });
expect(response.toString()).toStrictEqual(expectedResponse);
});
});
@@ -84,7 +83,7 @@ describe("httpRequest", () => {
expectedResponse: "continue",
});

await expect(httpRequest({ hostname, path, port })).rejects.toStrictEqual(
await expect(httpRequest({ hostname, path })).rejects.toStrictEqual(
Object.assign(new ProviderError("Error response received from instance metadata service"), { statusCode })
);
});
@@ -102,7 +101,7 @@ describe("httpRequest", () => {
return request;
}) as any);

await expect(httpRequest({ hostname, path, port })).rejects.toStrictEqual(
await expect(httpRequest({ hostname, path })).rejects.toStrictEqual(
new ProviderError("Unable to connect to instance metadata service")
);
});
@@ -131,7 +130,7 @@ describe("httpRequest", () => {
return request;
}) as any);

await expect(httpRequest({ hostname, path, port, timeout })).rejects.toStrictEqual(
await expect(httpRequest({ hostname, path, timeout })).rejects.toStrictEqual(
new ProviderError("TimeoutError from instance metadata service")
);
});
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ vi.mock("@smithy/url-parser");

describe(getInstanceMetadataEndpoint.name, () => {
let mockURL: string;
const mockEndpoint = { protocol: "http:", hostname: "localhost", port: "80" };
const mockEndpoint = { protocol: "http:", hostname: "localhost", port: 80, path: "" };

beforeEach(() => {
vi.mocked(parseUrl).mockReturnValue(mockEndpoint);
Original file line number Diff line number Diff line change
@@ -24,7 +24,7 @@ describe("staticStabilityProvider", () => {
return {
...input,
expiration: `Extending expiration count: ${extensionCount}`,
};
} as any;
};
})()
);
2 changes: 1 addition & 1 deletion packages/hash-blob-browser/src/index.spec.ts
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ describe("blobHasher", () => {
const blob = new Blob(["test-string"]);

class Hash {
public value: string;
public value: string = "";
update(value: string) {
this.value = value;
}
6 changes: 3 additions & 3 deletions packages/hash-stream-node/src/readableStreamHasher.spec.ts
Original file line number Diff line number Diff line change
@@ -22,8 +22,8 @@ describe(readableStreamHasher.name, () => {
class MockHashCalculator extends Writable {
constructor(
public readonly hash: Hash,
public readonly mockWrite,
public readonly mockEnd
public readonly mockWrite: any,
public readonly mockEnd: any
) {
super();
}
@@ -41,7 +41,7 @@ describe(readableStreamHasher.name, () => {

beforeEach(() => {
(HashCalculator as unknown as any).mockImplementation(
(hash) => new MockHashCalculator(hash, mockHashCalculatorWrite, mockHashCalculatorEnd)
(hash: Hash) => new MockHashCalculator(hash, mockHashCalculatorWrite, mockHashCalculatorEnd)
);
mockDigest.mockResolvedValue(mockHash);
});
Original file line number Diff line number Diff line change
@@ -16,6 +16,7 @@ describe(compressStream.name, () => {
const data = typeof chunk === "string" ? [chunk, compressionSuffix].join(compressionSeparator) : null;
asyncGzip.ondata(undefined, data, final);
}),
terminate() {}
};

beforeEach(() => {
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@ describe(compressStream.name, () => {
const testOutputStream = Readable.from(getGenerator(["input", "gzipped"])());

beforeEach(() => {
(vi.mocked(createGzip)).mockReturnValue(mockGzipFn);
(vi.mocked(createGzip)).mockReturnValue(mockGzipFn as any);
testInputStream.pipe = vi.fn().mockReturnValue(testOutputStream);
});

Original file line number Diff line number Diff line change
@@ -14,17 +14,17 @@ describe(compressString.name, () => {
const compressionSeparator = ".";

beforeEach(() => {
(vi.mocked(toUint8Array)).mockImplementation((data) => data);
vi.mocked(toUint8Array).mockImplementation((data) => data as any);
});

afterEach(() => {
vi.clearAllMocks();
});

it("should compress data with gzip", async () => {
(vi.mocked(gzip)).mockImplementation((data, callback) => {
vi.mocked(gzip).mockImplementation(((data: any, callback: any) => {
callback(null, [data, compressionSuffix].join(compressionSeparator));
});
}) as any);
const receivedOutput = await compressString(testData);
const expectedOutput = [testData, compressionSuffix].join(compressionSeparator);

@@ -38,9 +38,9 @@ describe(compressString.name, () => {
it("should throw an error if compression fails", async () => {
const compressionErrorMsg = "compression error message";
const compressionError = new Error(compressionErrorMsg);
(vi.mocked(gzip)).mockImplementation((data, callback) => {
vi.mocked(gzip).mockImplementation(((data: any, callback: any) => {
callback(compressionError);
});
}) as any);

await expect(compressString(testData)).rejects.toThrow(
new Error("Failure during compression: " + compressionErrorMsg)
Original file line number Diff line number Diff line change
@@ -18,7 +18,7 @@ describe(compressString.name, () => {
const testData = "test";

beforeEach(() => {
(vi.mocked(toUint8Array)).mockImplementation((data) => data);
(vi.mocked(toUint8Array)).mockImplementation((data: any) => data);
});

afterEach(() => {
Original file line number Diff line number Diff line change
@@ -83,7 +83,7 @@ describe(compressionMiddleware.name, () => {
});

it("compresses streaming blob", async () => {
const mockCompressedStream = "compressed-stream";
const mockCompressedStream = "compressed-stream" as any;
(vi.mocked(compressStream)).mockResolvedValueOnce(mockCompressedStream);

await compressionMiddleware(mockConfig, mockMiddlewareConfig)(mockNext, mockContext)({ ...mockArgs } as any);
@@ -120,7 +120,7 @@ describe(compressionMiddleware.name, () => {
});

it("compresses body", async () => {
const mockCompressedBody = "compressed-body";
const mockCompressedBody = "compressed-body" as any;
(vi.mocked(compressString)).mockResolvedValueOnce(mockCompressedBody);

await compressionMiddleware(mockConfig, mockMiddlewareConfig)(mockNext, mockContext)({ ...mockArgs } as any);
@@ -141,7 +141,7 @@ describe(compressionMiddleware.name, () => {
});

it("appends algorithm to existing Content-Encoding header", async () => {
const mockCompressedBody = "compressed-body";
const mockCompressedBody = "compressed-body" as any;
(vi.mocked(compressString)).mockResolvedValueOnce(mockCompressedBody);

const mockExistingContentEncoding = "deflate";
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ describe(getCompressionPlugin.name, () => {
const middlewareConfig = { encodings: [] };

it("applyToStack adds compressionMiddleware", () => {
const middlewareReturn = {};
const middlewareReturn = {} as any;
(vi.mocked(compressionMiddleware)).mockReturnValueOnce(middlewareReturn);

const plugin = getCompressionPlugin(config, middlewareConfig);
6 changes: 3 additions & 3 deletions packages/middleware-retry/src/AdaptiveRetryStrategy.spec.ts
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ describe(AdaptiveRetryStrategy.name, () => {
const mockDefaultRateLimiter = {
getSendToken: vi.fn(),
updateClientSendingRate: vi.fn(),
};
} as any;

beforeEach(() => {
vi.mocked(DefaultRateLimiter).mockReturnValue(mockDefaultRateLimiter);
@@ -85,13 +85,13 @@ describe(AdaptiveRetryStrategy.name, () => {

it("calls rateLimiter.getSendToken in beforeRequest", async () => {
expect(mockDefaultRateLimiter.getSendToken).toHaveBeenCalledTimes(0);
await mockedSuperRetry.mock.calls[0][2].beforeRequest();
await mockedSuperRetry.mock.calls[0][2]!.beforeRequest();
expect(mockDefaultRateLimiter.getSendToken).toHaveBeenCalledTimes(1);
});

it("calls rateLimiter.updateClientSendingRate in afterRequest", async () => {
expect(mockDefaultRateLimiter.updateClientSendingRate).toHaveBeenCalledTimes(0);
await mockedSuperRetry.mock.calls[0][2].afterRequest();
await mockedSuperRetry.mock.calls[0][2]!.afterRequest();
expect(mockDefaultRateLimiter.updateClientSendingRate).toHaveBeenCalledTimes(1);
});
});
10 changes: 5 additions & 5 deletions packages/node-config-provider/src/configLoader.spec.ts
Original file line number Diff line number Diff line change
@@ -20,11 +20,11 @@ describe("loadConfig", () => {
});

it("passes fromEnv(), fromSharedConfigFiles() and fromStatic() to chain", () => {
const mockFromEnvReturn = "mockFromEnvReturn";
const mockFromEnvReturn = "mockFromEnvReturn" as any;
vi.mocked(fromEnv).mockReturnValueOnce(mockFromEnvReturn);
const mockFromSharedConfigFilesReturn = "mockFromSharedConfigFilesReturn";
const mockFromSharedConfigFilesReturn = "mockFromSharedConfigFilesReturn" as any;
vi.mocked(fromSharedConfigFiles).mockReturnValueOnce(mockFromSharedConfigFilesReturn);
const mockFromStatic = "mockFromStatic";
const mockFromStatic = "mockFromStatic" as any;
vi.mocked(fromStatic).mockReturnValueOnce(mockFromStatic);
// Using Record<string, string | undefined> instead of NodeJS.ProcessEnv, in order to not get type errors in non node environments
const envVarSelector = (env: Record<string, string | undefined>) => env["AWS_CONFIG_FOO"];
@@ -49,7 +49,7 @@ describe("loadConfig", () => {
});

it("passes output of chain to memoize", () => {
const mockChainReturn = "mockChainReturn";
const mockChainReturn = "mockChainReturn" as any;
vi.mocked(chain).mockReturnValueOnce(mockChainReturn);
loadConfig({} as any);
expect(chain).toHaveBeenCalledTimes(1);
@@ -58,7 +58,7 @@ describe("loadConfig", () => {
});

it("returns output memoize", () => {
const mockMemoizeReturn = "mockMemoizeReturn";
const mockMemoizeReturn = "mockMemoizeReturn" as any;
vi.mocked(memoize).mockReturnValueOnce(mockMemoizeReturn);
expect(loadConfig({} as any)).toEqual(mockMemoizeReturn);
});
Original file line number Diff line number Diff line change
@@ -165,7 +165,7 @@ describe("fromSharedConfigFiles", () => {
it.each(["foo", "default"])("returns config value from %s profile", (profile) => {
vi.mocked(getProfileName).mockReturnValueOnce(profile);
return expect(fromSharedConfigFiles(configGetter)()).resolves.toBe(
loadedConfigData.configFile[profile][CONFIG_KEY]
(loadedConfigData.configFile as Record<string, { config_key: string }>)[profile][CONFIG_KEY]
);
});
});
2 changes: 1 addition & 1 deletion packages/node-config-provider/src/fromStatic.spec.ts
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ vi.mock("@smithy/property-provider", () => ({
}));

describe("fromStatic", () => {
const value = "default";
const value = "default" as any;
it("should convert static values to provider", async () => {
vi.mocked(convertToProvider).mockReturnValue(value);
fromStatic(value);
Loading