简体   繁体   中英

How to code this cli command such that the test pass?

What should I write in task.js such that this test in task.test.js pass?

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

When I type ./task help in command line I have to display text in usage on console. Currently task.js is blank. If anyone could guide me it would be a great help.

First you have to parse the command line input and for that you have to use process.argv() method.

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

Now run "./task help" on the shell you will see the output 'help' Using above you can parse your cli input. After that you can use if else or switch case statements for various inputs and executes them. For eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM