如何调试自定义的摩卡测试报告器?

问题描述

我正在写一个摩卡测试报告程序,我想将其用于定制的赛普拉斯测试文档。 哪种是调试报告程序代码的正确方法(也许使用intellij Idea)?

编辑 我尝试使用intellij Idea工具进行调试,在调试模式下运行cypress(打开和运行)。 我还尝试了IntelliJ Cypress插件专业版,该版本允许进行测试调试。

我无法在断点停下来。

所以我至少尝试打印一些调试日志,但是我看不到我的日志。

解决方法

我无法使用 Cypress,但我可以在 VSCode 中使用 Mocha。

Working example here

调试步骤:

  1. 为您的项目安装 ts-node 和 typescript:npm i ts-node typescript --save-dev

  2. 在您的 src 文件夹中使用以下内容创建 custom-reporter.ts:(取自 https://mochajs.org/api/tutorial-custom-reporter.html 并稍作修改)

import { reporters,Runner,Suite,Test } from 'mocha';

const { EVENT_RUN_BEGIN,EVENT_RUN_END,EVENT_TEST_FAIL,EVENT_TEST_PASS,EVENT_SUITE_BEGIN,EVENT_SUITE_END } = Runner.constants;

// This reporter outputs test results,indenting two spaces per suite
export class CustomReporter extends reporters.Base {
  private indents = 0;

  constructor(runner: Runner) {
    super(runner);
    const stats = runner.stats;

    runner
      .once(EVENT_RUN_BEGIN,() => {
        console.info('start');
      })
      .on(EVENT_SUITE_BEGIN,(suite: Suite) => {
        this.increaseIndent();
      })
      .on(EVENT_SUITE_END,(suite: Suite) => {
        this.decreaseIndent();
      })
      .on(EVENT_TEST_PASS,(test: Test) => {
        // Test#fullTitle() returns the suite name(s)
        // prepended to the test title
        console.log(`${this.indent()}pass: ${test.fullTitle()}`);
      })
      .on(EVENT_TEST_FAIL,(test: Test,err: any) => {
        console.log(`${this.indent()}fail: ${test.fullTitle()} - error: ${err.message}`);
      })
      .once(EVENT_RUN_END,() => {
        console.log(`end: ${stats.passes}/${stats.passes + stats.failures} ok`);
      });
  }

  private indent() {
    return Array(this.indents).join('  ');
  }

  private increaseIndent() {
    this.indents++;
  }

  private decreaseIndent() {
    this.indents--;
  }
}
  1. 我们将在运行时通过 ts-node 编译 custom-reporter.ts,但我们必须将 .js 作为报告者传递给 Mocha。 因此,我们按如下方式创建 index.js 并按如下方式导出我们的报告器:
    module.exports = require("./src/custom-reporter").CustomReporter;
  1. 如果您想在不进行调试的情况下运行,请将测试脚本添加到您的 package.json
 "scripts": {
    "test": "mocha -r ts-node/register specs/*.spec.ts --reporter index"
  },
  1. 在您的项目根目录中创建 .vscode/launch.json,并添加以下代码:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information,visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0","configurations": [
        {
            "type": "node","request": "launch","name": "Debug Mocha tests","cwd": "${workspaceRoot}","program": "${workspaceFolder}/node_modules/mocha/bin/_mocha","args": [
              "-r","ts-node/register","--reporter","index","${workspaceFolder}/specs/**/*.spec.ts"
            ],"protocol": "inspector","sourceMaps": true,"console": "integratedTerminal"
          },]
}
  1. 在 VSCode 中放置一些断点到 src/custom-reporter.ts

  2. 在 VSCode 中打开 Run and Debug 面板 (Ctrl+Shift+D),选择 Debug Mocha tests 并按下播放按钮

通过这种方式,您应该能够开始运行测试并在 VSCode 中找到断点。

干杯!