Jest: Test Driven Development
What is Test Driven Development, or TDD?
TDD is a process and form of programming that involves writing code that tests what an app should do. This type of programming minimizes time spent debugging an application.
Jest
Jest is a testing framework built on Javascript; it is mainly used with React and React Native based applications (Jest Framework Tutorial: How to use it | BrowserStack).
Learning How To Jest
Today, I dabbled in some TDD. I wanted to familiarize myself with this form of programming. I built a simple test case and function to pass that test:
Above I have the problem I want to solve. The problem states that I should nondestructively capitalize the first letter of the city and also alphabetize the letters. Note module.exports = allCap
; I am exporting this function from my App.js file, so I can import it into my test file. I will be referencing this function in the test that I will write.
Note const allCap = require('./app)
. I am importing the function from App.js into my test file.
I begin with test()
. Inside the parentheses I add the two arguments: 1. The test description; 2. The function that performs the test. Inside the function, I declare the variable city
and initialize it with 'jerusalem'
.
Here is where the fun happens:
I am going to need to check that values meet certain conditions. By using expect()
, I now have access to all of the “matchers” available.
Let’s break it down!
I am passing the function allCap
, along with city
passed in, into expect()
— so expect(allCap(city))
. Next I will need to chain the condition, which will be the “matcher” with the value passed in — toBe('aeeJlmrsu')
. So expect(allCap(city)).toBe('aeeJlmrsu')
translates to “expect the solution to allCap(city)
to be 'aeeJlmrsu'
”.
Passing and Failing Tests
Failed Test
This is what a failing test looks like (now, tests can fail for various reasons):
It looks like I forgot to capitalize the “j” in “Jerusalem” before I sorted the letters alphabetically. See what my test expected compared to what it actually received.
Passed Test
This is what a passing test looks like:
All green, baby!
Solution
console.log()
indicating I didn’t mutate city
If you can find a better, much shorter solution, please be my guest!