1

我想为我在查询器中制作的 CLI 编写单元测试。我想验证提示是否正确显示,在命令行中模拟选择,并验证共振是否正确。

4

1 回答 1

1

在尝试了一堆包,阅读了 SO,并制作了模拟之后,我找到了答案!

首先你需要做一个testInquirer.js

import { writeFileSync, unlinkSync } from "fs";
import * as child_process from "child_process";

const TEMP_FILE_PATH = "/tmp/";

export default async (
  command,
  inputs,
  { output, error },
  { timeout, nodeScript, nodeCommand } = {
    timeout: 100,
    nodeScript: false,
    nodeCommand: "node"
  }
) =>
  new Promise(async resolve => {
    let proc;
    let tmpFile = `${TEMP_FILE_PATH}${Math.random()}.js`;

    if (nodeScript) {
      writeFileSync(tmpFile, command);
      proc = child_process.exec(`${nodeCommand} ${tmpFile}`);
    } else {
      proc = child_process.exec(command);
    }

    proc.stdout.on("data", data => {
      output(data);
    });

    proc.stderr.on("data", data => {
      error(data);
    });

    const sendKeys = async inputs => {
      await inputs.reduce(
        (previousPromise, input) =>
          new Promise(async resolve => {
            if (previousPromise) {
              await previousPromise;
            }

            setTimeout(() => {
              proc.stdin.write(input);
              resolve();
            }, timeout);
          }),
        null
      );

      proc.stdin.end();
    };

    await sendKeys(inputs);
    proc.on("exit", code => {
      if (nodeScript) {
        unlinkSync(tmpFile);
      }
      resolve(code);
    });
  });

// https://www.tldp.org/LDP/abs/html/escapingsection.html
export const DOWN = "\x1B\x5B\x42";
export const UP = "\x1B\x5B\x41";
export const ENTER = "\x0D";
export const SPACE = "\x20";

然后你可以这样测试你的 CLI。

testInquirer 的 api 是:

  • command:用于运行 CLI 的命令('通常类似于 CDing 进入正确的目录并运行node .or yarn start
  • 输入:输入数组,以便发送到标准输入。您可以使用导出的助手(ENTER,DOWN等)或输入输入
  • 输出:传递一个jest.fn()将监听所有stdout输出的
  • 选择:
    • 超时:命令之间的超时

测试:

import run, { UP, DOWN, ENTER, SPACE } from '../testInquirer';

describe('cli', () => {
  it('runs', async () => {
    const outputMock = jest.fn();

    await run('yarn start', [
      // Choose "Babel Config Generator"
      SPACE,
      DOWN,

      // Choose "CodeFresh Config Generator"
      SPACE,

      // Next Question
      ENTER,

    ], outputMock);

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/Which Generators do you want to use/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/❯◯ Babel Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/❯◯ CodeFresh Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: Babel Config Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: CodeFresh Config Generator/)
    );
  })
})

如果你想测试一个接受函数输入的文件,它看起来像这样:

describe(runGenerator, () => {
  let outputMock;
  let errorMock;

  beforeEach(() => {
    outputMock = jest.fn();
    errorMock = jest.fn();
  });

  it.only('runs a generator', async () => {
    const runGeneratorPath = `${__dirname.replace(/(\s+)/g, '\\$1')}/../runGenerator.ts`;
    const code = await testInquirer(`
      const runGenerator = require("${runGeneratorPath}").default;
      console.error(runGenerator)
      runGenerator(${JSON.stringify(MOCK_GENERATOR)});
    `, [], { output: outputMock, error: errorMock }, {
      nodeScript: true,
      nodeCommand: 'ts-node'
    });

    expect(code).toBe(0);

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/RUNNING GENERATOR: Mock Generator/)
    );

    expect(outputMock).toBeCalledWith(
      expect.stringMatching(/Executing step:/)
    );
  })
})
于 2019-12-03T04:59:34.573 回答