Skip to content

[Feature]: Jest-Cli exports some util APIs #12456

Closed
@adamma1024

Description

@adamma1024

🚀 Feature Proposal

Proposal: jest-cli package export buildArgv API and init API, or adding callback/plugin system.

https://github.com/facebook/jest/blob/356b3b05b77f927b49e151302edbef6594d09a22/packages/jest-cli/src/cli/index.ts#L51-L86

https://github.com/facebook/jest/blob/34308ae21827a44916471106b4e3afdb3779cbb1/packages/jest-cli/src/init/index.ts#L40-L155

Motivation

My purpose is to do something else when invoke run API of jest-cli, like this:

async function run (maybeArgv, ...) {
  const argv = buildArgv(maybeArgv);

  if (argv.init) {
      await init();
      return;
  }

 // do something
}

As we can see, if I want to let it to work well, I should import buildArgv API and init API from jest-cli/build/cli/index and jest-cli/build/init
After v27, I noticed that jest-cli did not export them anymore. I'm so agreed that it's a great idea to just export APIs which were introduced in the document. But how can I solve this problem in an easy way? I think that I can only rewrite a jest-cli to finish it.
Which sounds so stupid.
So, can jest-cli support this workaround by exporting some util APIs, or adding a callback/plugin system?

Example

By exports in package.json ( the easiest way I think ):

  "exports": {
    ".": {
      "types": "./build/index.d.ts",
      "default": "./build/index.js"
    },
    "./package.json": "./package.json",
    "./bin/jest": "./bin/jest.js",
    "./util": "blabla"     // add this line
  },

By plugin system/ callback:

export async function run(
  maybeArgv?: Array<string>,
  project?: string,
  callback?: any, // add a callback
): Promise<void> {
  try {
    const argv = await buildArgv(maybeArgv);

    if (argv.init) {
      await init();
      return;
    }

    // use callback if it exists.
    if(callback) {
        callback(argv, project);
    } else {
        const projects = getProjectListFromCLIArgs(argv, project);

        const {results, globalConfig} = await runCLI(argv, projects);
        readResultsAndExit(results, globalConfig);
    }
  } catch (error: any) {
    clearLine(process.stderr);
    clearLine(process.stdout);
    if (error?.stack) {
      console.error(chalk.red(error.stack));
    } else {
      console.error(chalk.red(error));
    }

    exit(1);
    throw error;
  }
}

Pitch

The most important point is that I think jest really need a plugin system( or callback ) to ensure users can do something else easier.
The second point is a little "selfish" because jest doing that is really easier than me, lol. Otherwise, I must rewrite jest-cli in my project to do that.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions