From 605a2b26983d71b25532e428a8373b4569d76b1a Mon Sep 17 00:00:00 2001 From: LH Date: Fri, 13 Sep 2024 19:51:53 +0800 Subject: [PATCH] feat(cli): add callbacks to cli --- .../cli/src/swc/__tests__/callback.test.ts | 70 +++++++++++++++++++ packages/cli/src/swc/dir.ts | 8 ++- 2 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 packages/cli/src/swc/__tests__/callback.test.ts diff --git a/packages/cli/src/swc/__tests__/callback.test.ts b/packages/cli/src/swc/__tests__/callback.test.ts new file mode 100644 index 0000000..a2ebb90 --- /dev/null +++ b/packages/cli/src/swc/__tests__/callback.test.ts @@ -0,0 +1,70 @@ +import { swcDir } from "../index"; + +jest.mock("../compile", () => ({ + outputResult: jest.fn(), +})); + +let mockComplie: any; + +jest.mock("../dirWorker", () => ({ + __esModule: true, + default: () => mockComplie(), +})); + +const cliOptions: any = { + outDir: "./.temp/", + watch: false, + filenames: ["./src/swcx/"], + extensions: [".ts"], + stripLeadingPaths: true, + sync: true, +}; +const swcOptions: any = { + jsc: { + target: "esnext", + externalHelpers: false, + }, + module: { + type: "commonjs", + }, +}; + +describe("dir callbacks", () => { + it("onSuccess should be called", async () => { + mockComplie = () => Promise.resolve(1); // mock complie success + + const onSuccess = jest.fn(); + const onFail = jest.fn(); + + await swcDir({ + cliOptions: cliOptions, + swcOptions: swcOptions, + callbacks: { + onSuccess, + onFail, + }, + }); + + expect(onSuccess.mock.calls).toHaveLength(1); + expect(onFail.mock.calls).toHaveLength(0); + }); + + it("onFail should be called", async () => { + mockComplie = () => Promise.reject(new Error("fail")); // mock complie fail + + const onSuccess = jest.fn(); + const onFail = jest.fn(); + + await swcDir({ + cliOptions: cliOptions, + swcOptions: swcOptions, + callbacks: { + onSuccess, + onFail, + }, + }); + + expect(onSuccess.mock.calls).toHaveLength(0); + expect(onFail.mock.calls).toHaveLength(1); + }); +}); diff --git a/packages/cli/src/swc/dir.ts b/packages/cli/src/swc/dir.ts index df987fe..03c4c8d 100644 --- a/packages/cli/src/swc/dir.ts +++ b/packages/cli/src/swc/dir.ts @@ -101,7 +101,9 @@ async function initialCompilation( }); results.set(filename, result); } catch (err: any) { - console.error(err.message); + if (!callbacks?.onFail) { + console.error(err.message); + } results.set(filename, CompileStatus.Failed); } } @@ -114,7 +116,9 @@ async function initialCompilation( ); results.set(filename, result); } catch (err: any) { - console.error(err.message); + if (!callbacks?.onFail) { + console.error(err.message); + } results.set(filename, CompileStatus.Failed); } }