Test Cases for Main Course!
Greetings. So we are back with test cases and someone recently told me food > drinks, and why I am telling you this? Because test cases > functions, let's all hail to test case supremacy.
Enough of my nonsensical talk, let's dive straight into this!
JavaScript Testing with Jest
Now, don't get started on I didn't mentioned anything about jest or even javaScript before. That's how it goes here!
What is Jest?
Its an open-source JavaScript testing framework developed by Facebook. It has become a popular choice for testing JavaScript applications, offering a simple and powerful way to ensure the reliability and correctness of your code.
Few Key Features of jest:
Zero Configuration
Fast and Parallelised
Snapshot Testing
Mocking
Built-in Expectations
Support for Asynchronous Testing
Not, going deeper on these features in this blog, might cover them some other time.
Installing Jest
Getting Jest up and running is a breeze. If you haven't installed it yet, run the following command in your project directory:
npm install --save-dev jest
Writing Your First Test
Let's create a simple function and test it. In a file named math.js
, write a function:
// math.js
function add(a, b) {
return a + b;
}
module.exports = add;
Now, let's write a Jest test for this function. Create a file named math.test.js
:
// math.test.js
const add = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
Running Jest
Run your tests with:
npx jest
Jest will execute your test, and you should see a delightful green check mark indicating success.
What's Next?
Test Cases for Dessert!
Connect with me on LinkedIn.
Subscribe to my newsletter
Read articles from Shivam Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shivam Gupta
Shivam Gupta
I am a developer who likes to do things...