Member-only story
Build a Time-Tracking CLI Application Using a Test-Driven Development
TDD with the oclif testing library
While writing a CLI tool can be a lot of fun, the initial setup and boilerplate — parsing arguments and flags, validation, subcommands — is generally the same for every CLI, and it’s a drag. That’s where the oclif framework saves the day. The boilerplate for writing a single-command or multi-command CLI melts away, and you can quickly get into the code that you actually want to write.
But wait — there’s more! oclif
also has a testing framework that lets you execute your CLI the same way a user would, capturing standard output and errors so that you can test expectations. In this article, I’ll show you how to write and test an oclif
CLI application with ease.
What Are We Going To Build?
We’re all tired of working on the typical TODO application. Instead, let’s build something different but simple. We’ll use a test-driven development (TDD) approach to build a time-tracking application. Our CLI will let us do the following:
- Add projects
- Start and end timers on those projects
- View the total spend on a project
- View the time spent on each entry for a given project
Here’s what a sample interaction with the time-tracker
CLI looks like:
~ time-tracker add-project project-one
Created new project "project-one"~ time-tracker start-timer project-one
Started a new time entry on "project-one"~ time-tracker start-timer project-two
> Error: Project "project-two" does not exist~ time-tracker add-project project-two
Created new project "project-two"~ time-tracker start-timer project-two
Started a new time entry on "project-two"~ time-tracker end-timer project-two
Ended time entry for "project-two"~ time-tracker list-projects
project-one (0h 0m 13.20s)
- 2021-09-20T13:13:09.192Z - 2021-09-20T13:13:22.394Z (0h 0m 13.20s)
project-two (0h 0m 7.79s)
- 2021-09-20T13:13:22.394Z - 2021-09-20T13:13:30.189Z (0h 0m 7.79s)