【问题标题】:How to code this cli command such that the test pass?如何编写此 cli 命令以使测试通过?
【发布时间】:2022-01-14 05:59:56
【问题描述】:

我应该在task.js 中写些什么才能使task.test.js 中的这个测试通过?

const fs = require("fs");
const { execSync } = require("child_process");

let deleteFile = (path) => {
  try {
    fs.unlinkSync(path);
  } catch (err) {}
};

beforeEach(() => {
  deleteFile(`${__dirname}/task.txt`);
  deleteFile(`${__dirname}/completed.txt`);
});

let tasksTxtCli = (...args) => [`${__dirname}/task.sh`, ...args].join(" ");

let usage = `Usage :-
$ ./task add 2 hello world    # Add a new item with priority 2 and text "hello world" to the list
$ ./task ls                   # Show incomplete priority list items sorted by priority in ascending order
$ ./task del INDEX            # Delete the incomplete item with the given index
$ ./task done INDEX           # Mark the incomplete item with the given index as complete
$ ./task help                 # Show usage
$ ./task report               # Statistics`;

test("prints help when no additional args are provided", () => {
  let received = execSync(tasksTxtCli()).toString("utf8");
  expect(received).toEqual(expect.stringContaining(usage));
});

当我在命令行中输入./task help 时,我必须在控制台上的usage 中显示文本。目前task.js 为空白。如果有人可以指导我,那将是一个很大的帮助。

【问题讨论】:

    标签: javascript node.js jestjs command-line-interface


    【解决方案1】:

    首先你必须解析命令行输入,为此你必须使用 process.argv() 方法。

     const arguments = process.argv.slice(2); // delete first two arguments as the..
     // first one is the process execution path
     //second one is the path for the js file
    
     console.log(arguments[0]);
    

    现在在 shell 上运行“./task help”,您将看到输出“help” 使用上面你可以解析你的 cli 输入。 之后,您可以对各种输入使用 if else 或 switch case 语句并执行它们。例如

    if(arguments[0] === "help") {
        const help = `Usage :-
        $ ./task add 2 hello world    # Add a new item with priority 2 and text "hello world" to the list
        $ ./task ls                   # Show incomplete priority list items sorted by priority in ascending order
        $ ./task del INDEX            # Delete the incomplete item with the given index
        $ ./task done INDEX           # Mark the incomplete item with the given index as complete
        $ ./task help                 # Show usage
        $ ./task report               # Statistics`;
    
        console.log(help);
    }
    // like that you can do for others
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      相关资源
      最近更新 更多