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

Switching to vitest #1369

Merged
merged 17 commits into from
Dec 11, 2023
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
4 changes: 2 additions & 2 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ jobs:
parallel: true
- name: Build
run: yarn build
- name: Vitest compatibility
run: yarn test:vi
- name: Compatibility test
run: yarn test:compat
- name: Integration test
run: yarn test:int
- name: Issue 952
Expand Down
11 changes: 0 additions & 11 deletions jest.config.json

This file was deleted.

19 changes: 9 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,18 @@
"build:client": "yarn tsnode example/generate-client.ts && yarn prettier example/example.client.ts --write",
"build:license": "yarn tsnode tools/license.ts",
"build:logo": "yarn tsnode tools/startup-logo.ts",
"test": "yarn test:types && yarn test:jest && yarn test:badge",
"test:int": "yarn --cwd tests/integration && jest tests/integration",
"test": "yarn test:types && yarn test:unit && yarn test:badge",
"test:int": "yarn --cwd tests/integration && vitest run tests/integration",
"test:952": "yarn --cwd tests/issue952 && yarn --cwd tests/issue952 test",
"test:esm": "yarn --cwd tests/esm && jest tests/esm",
"test:vi": "yarn --cwd tests/vitest && yarn --cwd tests/vitest test",
"test:u": "yarn test:jest -u && yarn test:badge",
"test:esm": "yarn --cwd tests/esm && vitest run tests/esm",
"test:compat": "yarn --cwd tests/compat && yarn --cwd tests/compat test",
"test:u": "yarn test:unit -u && yarn test:badge",
"test:types": "tsc --noEmit",
"test:jest": "jest tests/unit tests/system",
"test:unit": "vitest run tests/unit tests/system",
"test:badge": "make-coverage-badge --output-path coverage.svg",
"lint": "eslint src example tests tools && yarn prettier *.md --check",
"mdfix": "prettier *.md --write",
"cleanup": "rm -rf tests/**/node_modules",
"cleanup": "rm -rf tests/**/node_modules coverage tests/**/coverage",
"tsnode": "node -r @swc-node/register",
"precommit": "yarn lint && yarn test && yarn build && git add example/example.* LICENSE coverage.svg",
"prepublishOnly": "yarn lint && yarn test && yarn build",
Expand Down Expand Up @@ -126,20 +126,19 @@
"@arethetypeswrong/cli": "^0.13.0",
"@swc-node/register": "^1.6.8",
"@swc/core": "^1.3.92",
"@swc/jest": "^0.2.29",
"@tsconfig/node18": "^18.2.1",
"@types/compression": "^1.7.5",
"@types/cors": "^2.8.14",
"@types/express": "^4.17.17",
"@types/express-fileupload": "^1.4.4",
"@types/has-ansi": "^5.0.0",
"@types/http-errors": "^2.0.2",
"@types/jest": "^29.5.4",
"@types/node": "^20.8.4",
"@types/ramda": "^0.29.3",
"@types/triple-beam": "^1.3.2",
"@typescript-eslint/eslint-plugin": "^6.6.0",
"@typescript-eslint/parser": "^6.6.0",
"@vitest/coverage-istanbul": "^1.0.4",
"chalk": "^4.1.2",
"compression": "^1.7.4",
"cors": "^2.8.5",
Expand All @@ -156,14 +155,14 @@
"has-ansi": "^4.0.1",
"http-errors": "^2.0.0",
"husky": "^8.0.3",
"jest": "^29.6.4",
"make-coverage-badge": "^1.2.0",
"mockdate": "^3.0.5",
"prettier": "3.1.1",
"strip-ansi": "^6.0.1",
"tsd": "^0.29.0",
"tsup": "^8.0.0",
"typescript": "^5.2.2",
"vitest": "^1.0.4",
"winston": "^3.10.0",
"zod": "^3.22.3"
},
Expand Down
23 changes: 16 additions & 7 deletions src/testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,21 @@ export const makeResponseMock = <RES extends Record<string, any>>({
return responseMock;
};

export const makeLoggerMock = <LOG extends Record<string, any>>({
fnMethod,
loggerProps,
}: {
fnMethod: MockFunction;
loggerProps?: LOG;
}) =>
({
info: fnMethod(),
warn: fnMethod(),
error: fnMethod(),
debug: fnMethod(),
...loggerProps,
}) as Record<keyof AbstractLogger, MockOverrides> & LOG;

interface TestEndpointProps<REQ, RES, LOG> {
/** @desc The endpoint to test */
endpoint: AbstractEndpoint;
Expand Down Expand Up @@ -121,13 +136,7 @@ export const testEndpoint = async <
).fn;
const requestMock = makeRequestMock({ fnMethod: fnMethod, requestProps });
const responseMock = makeResponseMock({ fnMethod: fnMethod, responseProps });
const loggerMock = {
info: fnMethod(),
warn: fnMethod(),
error: fnMethod(),
debug: fnMethod(),
...loggerProps,
} as Record<keyof AbstractLogger, MockOverrides> & LOG;
const loggerMock = makeLoggerMock({ fnMethod, loggerProps });
const configMock = {
cors: false,
logger: loggerMock,
Expand Down
7 changes: 7 additions & 0 deletions tests/compat/jest.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"transform": {
"^.+\\.ts$": "@swc/jest"
},
"testEnvironment": "node",
"verbose": true
}
32 changes: 32 additions & 0 deletions tests/compat/jest.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { defaultEndpointsFactory, testEndpoint } from "express-zod-api";
import { z } from "zod";

declare module "express-zod-api" {
interface MockOverrides extends jest.Mock {}
}

describe("Jest compatibility test", () => {
describe("testEndpoint()", () => {
test.each([undefined, jest.fn])(
"should support jest.fn %#",
async (fnMethod) => {
const endpoint = defaultEndpointsFactory.build({
method: "post",
input: z.object({ n: z.number() }),
output: z.object({ inc: z.number() }),
handler: async ({ input }) => ({ inc: input.n + 1 }),
});
const { responseMock } = await testEndpoint({
endpoint,
requestProps: { method: "POST", body: { n: 123 } },
fnMethod,
});
expect(responseMock.status).toHaveBeenCalledWith(200);
expect(responseMock.json).toHaveBeenCalledWith({
status: "success",
data: { inc: 124 },
});
},
);
});
});
7 changes: 5 additions & 2 deletions tests/vitest/package.json → tests/compat/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"private": true,
"version": "0.0.0",
"scripts": {
"test": "vitest run"
"test": "jest"
},
"dependencies": {
"express-zod-api": "link:../..",
Expand All @@ -13,6 +13,9 @@
"zod": "^3"
},
"devDependencies": {
"vitest": "^1.0.0-beta.4"
"jest": "^29.7.0",
"@types/jest": "^29.5.11",
"@swc/core": "^1.3.100",
"@swc/jest": "^0.2.29"
}
}
File renamed without changes.
29 changes: 11 additions & 18 deletions tests/esm/quick-start.spec.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { spawn } from "node:child_process";
import { givePort, waitFor } from "../helpers";
import { afterAll, afterEach, describe, expect, test } from "vitest";

describe("ESM Test", () => {
let quickStart: ChildProcessWithoutNullStreams;
describe("ESM Test", async () => {
let out = "";
const listener = (chunk: Buffer) => {
out += chunk.toString();
};
const quickStart = spawn(
"node",
["--loader", "@swc-node/register/esm", "quick-start.ts"],
{ cwd: "./tests/esm" },
);
quickStart.stdout.on("data", listener);
quickStart.stderr.on("data", listener);
const port = givePort("esm");

beforeAll(() => {
quickStart = spawn(
"node",
["--loader", "@swc-node/register/esm", "quick-start.ts"],
{ cwd: "./tests/esm" },
);
quickStart.stdout.on("data", listener);
quickStart.stderr.on("data", listener);
});
await waitFor(() => out.indexOf(`Listening ${port}`) > -1);

afterAll(async () => {
quickStart.stdout.removeListener("data", listener);
Expand All @@ -32,11 +30,6 @@ describe("ESM Test", () => {
});

describe("Quick Start from Readme", () => {
test("Should listen", async () => {
await waitFor(() => out.indexOf(`Listening ${port}`) > -1);
expect(true).toBeTruthy();
});

test("Should handle valid GET request", async () => {
const response = await fetch(
`http://localhost:${port}/v1/hello?name=Rick`,
Expand Down
44 changes: 26 additions & 18 deletions tests/express-mock.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,38 @@
// @see https://github.com/swc-project/jest/issues/14#issuecomment-970189585
// @see https://github.com/swc-project/vi/issues/14#issuecomment-970189585
import { Mock, vi } from "vitest";

const expressJsonMock = jest.fn();
const compressionMock = jest.fn();
const fileUploadMock = jest.fn();
jest.mock("compression", () => compressionMock);
jest.mock("express-fileupload", () => fileUploadMock);
const expressJsonMock = vi.fn();
const compressionMock = vi.fn();
const fileUploadMock = vi.fn();

const staticHandler = jest.fn();
const staticMock = jest.fn(() => staticHandler);
vi.mock("compression", () => ({ default: compressionMock }));
vi.mock("express-fileupload", () => ({ default: fileUploadMock }));

let appMock: Record<"disable" | "use" | "get" | "post" | "options", jest.Mock>;
const staticHandler = vi.fn();
const staticMock = vi.fn(() => staticHandler);

const appCreatorMock = () => {
let appMock: Record<
"disable" | "use" | "get" | "post" | "put" | "patch" | "delete" | "options",
Mock
>;

const expressMock = () => {
appMock = {
disable: jest.fn(() => appMock),
use: jest.fn(() => appMock),
get: jest.fn(),
post: jest.fn(),
options: jest.fn(),
disable: vi.fn(() => appMock),
use: vi.fn(() => appMock),
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
patch: vi.fn(),
delete: vi.fn(),
options: vi.fn(),
};
return appMock;
};
appCreatorMock.json = () => expressJsonMock;
appCreatorMock.static = staticMock;
expressMock.json = () => expressJsonMock;
expressMock.static = staticMock;

const expressMock = jest.mock("express", () => appCreatorMock);
vi.mock("express", () => ({ default: expressMock }));

export {
compressionMock,
Expand Down
3 changes: 1 addition & 2 deletions tests/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import jestConfig from "../jest.config.json";
import { z } from "zod";
import { SchemaHandler, walkSchema } from "../src/schema-walker";

Expand All @@ -22,7 +21,7 @@ export const waitFor = async (cb: () => boolean) =>
const timeout = setTimeout(() => {
clearInterval(timer); // eslint-disable-line @typescript-eslint/no-use-before-define
reject();
}, jestConfig.testTimeout);
}, 10000);
const timer = setInterval(() => {
if (cb()) {
clearInterval(timer);
Expand Down
21 changes: 10 additions & 11 deletions tests/http-mock.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,30 @@
import http from "node:http";
import https from "node:https";
import { MockInstance, vi } from "vitest";

const realHttpCreator = http.createServer;
const realHttpsCreator = https.createServer;

let httpListenSpy: jest.SpyInstance;
let httpsListenSpy: jest.SpyInstance;
let httpListenSpy: MockInstance;
let httpsListenSpy: MockInstance;

jest.spyOn(http, "createServer").mockImplementation((app) => {
vi.spyOn(http, "createServer").mockImplementation((app) => {
const server = realHttpCreator(app);
httpListenSpy = jest.spyOn(server, "listen").mockImplementation(({}, cb) => {
httpListenSpy = vi.spyOn(server, "listen").mockImplementation(({}, cb) => {
cb?.call(null);
return server;
});
return server;
});

const createHttpsServerSpy = jest
const createHttpsServerSpy = vi
.spyOn(https, "createServer")
.mockImplementation(({}, app) => {
const server = realHttpsCreator(app);
httpsListenSpy = jest
.spyOn(server, "listen")
.mockImplementation(({}, cb) => {
cb?.call(null);
return server;
});
httpsListenSpy = vi.spyOn(server, "listen").mockImplementation(({}, cb) => {
cb?.call(null);
return server;
});
return server;
});

Expand Down
27 changes: 11 additions & 16 deletions tests/integration/quick-start.spec.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import { ChildProcessWithoutNullStreams, spawn } from "node:child_process";
import { spawn } from "node:child_process";
import { givePort, waitFor } from "../helpers";
import { afterAll, afterEach, describe, expect, test } from "vitest";

describe("Integration Test", () => {
let quickStart: ChildProcessWithoutNullStreams;
describe("Integration Test", async () => {
let out = "";
const listener = (chunk: Buffer) => {
out += chunk.toString();
};
const quickStart = spawn(
"node",
["-r", "@swc-node/register", "quick-start.ts"],
{ cwd: "./tests/integration" },
);
quickStart.stdout.on("data", listener);
quickStart.stderr.on("data", listener);
const port = givePort("example");

beforeAll(() => {
quickStart = spawn("node", ["-r", "@swc-node/register", "quick-start.ts"], {
cwd: "./tests/integration",
});
quickStart.stdout.on("data", listener);
quickStart.stderr.on("data", listener);
});
await waitFor(() => out.indexOf(`Listening ${port}`) > -1);

afterAll(async () => {
quickStart.stdout.removeListener("data", listener);
Expand All @@ -30,11 +30,6 @@ describe("Integration Test", () => {
});

describe("Quick Start from Readme", () => {
test("Should listen", async () => {
await waitFor(() => out.indexOf(`Listening ${port}`) > -1);
expect(true).toBeTruthy();
});

test("Should handle valid GET request", async () => {
const response = await fetch(
`http://localhost:${port}/v1/hello?name=Rick`,
Expand Down
Loading