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

问题描述 投票:1回答:3

如何使用jest.run()jest.runCLI()以编程方式运行所有测试?什么是我养活作为参数?

我试图找到文档中有关他们,但失败。

如果上述功能不工作,我应该怎么称呼,如果我想通过程序运行开玩笑?

jestjs
3个回答
4
投票

不应该以编程方式运行的玩笑。或许它会在未来。

尝试运行以下内容:

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);
  });

如在success回调then一个对象将被传递,含有globalConfigresults密钥。对他们看看,也许它会帮助你。


1
投票

这里的例子,从我的岗位上How to run Jest programmatically in node.js (Jest JavaScript API)

这次使用的打字稿。

Install the dependencies

npm i -S jest-cli
npm i -D @types/jest-cli @types/jest

Make a call

import {runCLI} from 'jest-cli';
import ProjectConfig = jest.ProjectConfig;


const projectRootPath = '/path/to/project/root';

// Add any Jest configuration options here
const jestConfig: ProjectConfig = {
 roots: ['./dist/tests'],
 testRegex: '\\.spec\\.js$'
};

// Run the Jest asynchronously
const result = await runCLI(jestConfig as any, [projectRootPath]);

// Analyze the results
// (see typings for result format)
if (result.results.success) {
  console.log(`Tests completed`);
} else {
  console.error(`Tests failed`);
}

此外,关于@PeterDanis答案,我不知道玩笑会拒绝在一个失败的测试情况的​​承诺。在我的经验,将与result.results.success === false resovle。


1
投票

从我迄今经历,利用run()需要你定义一个静态的配置,然后传递参数就像你通常会使用Jest CLI来开玩笑了。

利用runCLI()允许你动态地创建一个配置并将其提供给开玩笑。

我选择了前者,只是因为我想只露出几个的玩笑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);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.