使用 jest.run() 或 jest.runCLI() 运行所有测试或以编程方式运行 jest 的方法

lmc*_*lmc 9 jestjs

如何以编程方式使用jest.run()jest.runCLI()运行所有测试?我应该用什么作为论证?

我试图找到有关它们的文档但失败了。

如果上述功能不起作用,如果我想以编程方式运行 jest 应该调用什么?

Pet*_*nis 7

Jest 不应该以编程方式运行。也许将来会。

尝试运行以下:

const jest = require("jest");

const options = {
  projects: [__dirname],
  silent: true,
};

jest
  .runCLI(options, options.projects)
  .then((success) => {
    console.log(success);
  })
  .catch((failure) => {
    console.error(failure);
  });
Run Code Online (Sandbox Code Playgroud)

successthen回调对象将被传递,含有globalConfigresults密钥。看看他们,也许它会帮助你。


小智 5

根据我目前的经验,使用run()需要定义一个静态配置,然后像通常使用Jest CLI一样将参数传递给 Jest 。

UtilizingrunCLI()允许您动态创建配置并将其提供给 Jest。

我选择前者只是因为我只想为全局配置公开一些 Jest CLI 选项:

import jest from "jest";
import { configPaths } from "../_paths";
import { Logger } from "../_utils";

process.env.BABEL_ENV = "test";
process.env.NODE_ENV = "test";

const defaultArgs = ["--config", configPaths.jestConfig];

const log = new Logger();

const resolveTestArgs = async args => {
  let resolvedArgs = [];

  if (args.file || args.f) {
    return [args.file || args.f, ...defaultArgs];
  }

  // updates the snapshots
  if (args.update || args.u) {
    resolvedArgs = [...resolvedArgs, "--updateSnapshot"];
  }

  // tests the coverage
  if (args.coverage || args.cov) {
    resolvedArgs = [...resolvedArgs, "--coverage"];
  }

  // runs the watcher
  if (args.watch || args.w) {
    resolvedArgs = [...resolvedArgs, "--watch"];
  }

  // ci arg to update default snapshot feature
  if (args.ci) {
    resolvedArgs = [...resolvedArgs, "--ci"];
  }

  // tests only tests that have changed
  if (args.changed || args.ch) {
    resolvedArgs = [...resolvedArgs, "--onlyChanged"];
  }

  return [...defaultArgs, ...resolvedArgs];
};

export const test = async cliArgs => {
  try {
    const jestArgs = await resolveTestArgs(cliArgs);
    jest.run(jestArgs);
  } catch (error) {
    log.error(error);
    process.exit(1);
  }
};
Run Code Online (Sandbox Code Playgroud)