---
title: 'JavaScript Unit Testing Tutorial for Beginners'
source: 'https://youtube.com/watch?v=zuKbR4Q428o'
video_id: 'zuKbR4Q428o'
date: 2026-08-05
duration_sec: 2911
---

# JavaScript Unit Testing Tutorial for Beginners

> Source: [JavaScript Unit Testing Tutorial for Beginners](https://youtube.com/watch?v=zuKbR4Q428o)

## Summary

This comprehensive course introduces JavaScript unit testing from the ground up, covering fundamental concepts, best practices, and hands-on examples. Instructor Mosh Hamedani guides beginners through writing and running tests, exploring test-driven development, and using tools like Vitest and VS Code. The course emphasizes building a solid foundation before moving to framework-specific testing.

### Key Points

- **Course Introduction** [00:02] — Mosh Hamedani introduces a 4-hour comprehensive JavaScript unit testing course designed for beginners, promising to take learners from zero to hero with practical examples and exercises.
- **Prerequisites** [01:24] — No prior unit testing experience needed, but basic modern JavaScript knowledge (import/export, promises, async/await) is required. The course focuses on fundamentals, not frontend or backend testing.
- **Course Structure** [02:07] — The course covers basics, core techniques (positive/negative, boundary, parameterized testing), mocks/fakes, and static analysis tools (ESLint, Prettier, TypeScript). It prepares learners for React and Node testing courses.
- **Foundation for Testing** [03:44] — The course provides a rock-solid foundation for testing JavaScript code, applicable to libraries, frontend (React), and backend (Node) testing.
- **Course Recommendations** [04:12] — Beginners should follow lessons sequentially and complete exercises. Experienced developers might skip around but risk bad habits. The course can be completed in a day.
- **Environment Setup** [05:08] — Download Node.js from nodejs.org and Visual Studio Code. Clone the starter project from GitHub (mosh-hamedani) to follow along.
- **Section Overview** [06:35] — This section covers what unit testing is, benefits, arguments against, types of tests, tooling (Vitest), setting up Vitest, writing first tests, TDD, running tests efficiently, VS Code shortcuts, and code coverage.
- **What is Unit Testing?** [08:23] — Unit testing is automated testing where code checks if other code works as expected. It's faster than manual testing and can run thousands of tests in seconds.
- **Benefits of Unit Testing** [09:38] — Benefits include early bug detection (cheaper to fix), confident refactoring, consideration of edge cases, and documentation of function behavior.
- **Extreme Viewpoints** [11:08] — Both no-testing and test-everything extremes are costly. A pragmatic balance is needed, considering project uniqueness and time/resource constraints.
- **Unit Testing as Investment** [12:50] — Unit testing is an investment in software quality. Poor tests are a waste; good tests are maintainable, robust, and trustworthy.
- **Types of Tests** [13:46] — Unit tests verify individual units in isolation; integration tests verify units working together; end-to-end tests simulate real user interactions. The testing pyramid suggests more unit tests than integration, more integration than e2e.
- **Testing Pyramid Trade-offs** [15:46] — As you go up the pyramid, tests are slower but give more confidence. Unit tests are fast and can run frequently; e2e tests are slow but high confidence.
- **Testing Frameworks** [16:41] — Testing frameworks include test runners, assertion libraries, mocking tools, coverage tools. Examples: Jest, Mocha, Jasmine, Vitest, Cypress, Playwright. Vitest is used in this course due to modern ESM support and Jest-like API.
- **Installing Vitest** [18:28] — Install Vitest as a dev dependency using npm. Add a test script in package.json: "test": "vitest".
- **Writing First Test** [19:48] — Create a test folder and a test file (e.g., intro.test.js). Use describe for test suite, test/it for test cases, expect for assertions. Structure tests with AAA (Arrange, Act, Assert).
- **AAA Pattern** [22:59] — Arrange: set up data/config. Act: perform action. Assert: check outcome. Example: TV off test - arrange (turn on), act (press power), assert (verify off).
- **Simplifying Tests** [25:45] — For simple cases, combine arrange/act/assert into one line. Use vertical line breaks to separate sections for readability.
- **Running Tests** [26:25] — Run npm test or npm t. Passing tests show green tick, failing show red cross. Test names should clearly describe the scenario.
- **Refactoring with Confidence** [28:13] — Unit tests allow refactoring with confidence. After refactoring, run tests to ensure behavior unchanged. Deliberately introduce a bug to verify tests catch it.
- **Exercise: FizzBuzz** [29:13] — Write tests for fizzBuzz function covering all execution paths: divisible by 3 and 5, only 3, only 5, neither. Use technique of introducing a bug to ensure test/production sync.
- **Test-Driven Development (TDD)** [35:04] — TDD is test-first approach: write failing test, write minimal code to pass, refactor. Benefits: 100% coverage, prevents over-engineering. But can be difficult for beginners; course focuses on code-first.
- **TDD Example: Calculate Average** [35:49] — Write tests for calculateAverage: empty array returns NaN, single element returns that element, two elements returns average, three elements returns average. Implement incrementally.
- **TDD Exercise: Factorial** [42:06] — Implement factorial using TDD: test cases for 0, 1, 2, 3, 4, negative. Write minimal code each step, eventually use recursion.
- **Course Promotion** [47:11] — The full 4-hour course covers advanced techniques: positive/negative testing, boundary testing, parameterized tests, async testing, mocks/spies, static analysis tools (Prettier, ESLint, TypeScript, Husky). Includes certificate and 30-day money-back guarantee.

### Conclusion

This course provides a solid foundation in JavaScript unit testing, emphasizing practical skills and best practices. By the end, learners can write effective tests, use TDD, and improve code quality, preparing them for more advanced testing scenarios.

## Transcript

welcome to mastering JavaScript unit testing in this comprehensive 4-Hour course I will take you on an exciting Journey where we will explore everything the very Basics to more Advanced Techniques if you're looking for a
comprehensive easy to follow well organized and practical course that takes you from Zero to Hero this is the right JavaScript unit testing course for you this course is packed with real world examples and a ton of Hands-On
exercises giving you plenty of opportunities to practice what you learn by the end of this course you'll have a strong foundation in unit testing you'll be able to significantly reduce bugs and improve the overall quality of your code
this expertise will set you apart in the world of software development opening doors to exciting opportunities and challenges so if you're ready to unlock the full potential of JavaScript unit testing and elevate your coding skills
join me in this exciting Journey I'm msh hamadani a software engineer with over 20 years of experience and I've taught Millions how to code and become professional software Engineers through my YouTube channel and online school CWI
mar.com if you're new here make sure to subscribe as I upload new videos all the time now let's jump in and get [Music]
started now to take this course you don't need any familiarity with unit testing at all in fact fact I've designed this course specifically for people who have never done unit testing because they find the idea intimidating
so I'm going to teach you everything from the ground up but to take this course you should have a basic understanding of modern JavaScript that means you should be comfortable with Concepts like importing and exporting
promises acing can weight and so on if you need to brush up on any of these Concepts check out the JavaScript series on my website so that's all about the prerequisites next we're going to talk about the course
how I've structured this course this course serves as the rock solid foundation for unit testing in JavaScript applications however I want to clarify something up front we won't be testing a front end or a backend here
because our primary focus is on nailing those fundamental unit testing Concepts and best practices that often get overlooked in many other courses this is where a lot of folks stumble when it comes to unit testing they rush
into testing react or node without grasping the essential foundations and best practices so in this course my goal is to equip you with a robust Foundation once you have completed this course you'll be well prepared to tackle my
other courses on testing react or Noe now here's our road map for this course we'll kick things off by getting you familiar with the basics of unit testing so in the first section we'll cover what unit testing is what are its benefits
and what are the common arguments against it then we'll see unit testing in action you will learn how to write basic tests and run them next up we'll delve deeper into core unit testing techniques and best practices we'll
cover Concepts like positive and negative testing boundary testing parameterized testing and so on then we'll explore how to use mocks or fakes to isolate our code during tests this is a very important technique used in unit
testing in the final section we'll explore some handy static analysis tools like eslint prier and typescript these tools help you elevate the quality of your code and reduce the need for extensive test cases
a rock solid foundation for testing JavaScript code if your goal is to write JavaScript libraries you can take what you learn in this course and use it to test your libraries if you're a front and developer and want to learn how to
covered I'm planning to create a dedicated course on the topic and Chances Are by the time you're watching this course my react testing course is already published as for backend testing I've covered it in my note course so at
this point I'm not planning to create a separate course on the to make the most of this course if you're brand new to unit testing the
best approach is to follow the lessons in order and complete the exercises along the way it'll help you build a strong Foundation however if you already have some experience you might be tempted to jump around and focus on
specific lessons while that's an option because the course is well structured I would like to advise you against it why well you might unknowingly have some bad habits or be using less than optimal practices as your instructor I strongly
recommend going through all the lessons sequentially the Fantastic part is that so you can easily complete it in a single day plus it's full of practical examples and exercises so you're not going to get bored with fluff content
all right now that we're on the same page our next step is setting up our page our next step is setting up our testing setting up our testing environment first head over to nodejs.org and download the
latest version of note now in this course just like my other courses I'll be using visual studio code or vs code as my editor you're welcome to use your preferred editor but in this course I'm going to show you a ton of shortcuts for
increasing your productivity so while not necessary I recommend you to not necessary I recommend you to download and install Visual Studio code all right before we move on to the next section I want you to download the
starter project I have created for this course so head over to github.com - hamadani here go to repositories and search for JavaScript D
testing here we have two repositories the started project and the finished project the finished project contains the solution to all the exercises I have created for you so let's start with the starter
project then go to code clone this URL next open a terminal window and run get clone followed by the URL all right good so here we have this folder JavaScript testing starter just
open this with vs code and you're good to unit testing JavaScript course this section is going to be your gateway to
the world of unit testing we'll kick things off by talking about what is unit testing what are its benefits and what are common arguments against it then we'll talk about different types of tests we encounter in real world
applications once we've got the theory covered we'll talk about the tooling we'll explore various testing Frameworks out there in this course we'll be using Vest which is a relatively new testing framework that has gained popularity but
the concepts you will learn in this course apply to other testing Frameworks like just as well so next we'll set up v test and write our first unit tests you will see unit testing and its benefits in action then I will introduce you to
the con concept of test driven development or tddd we'll talk about the benefits as well as a few misconceptions about tdd next I will show you various ways to run your tests efficiently this is a key skill you need to have
especially when you deal with broken tests you should be able to quickly filter your tests and focus on one or a few at a time now every season developer is expected to know how to navigate their code base quickly and smoothly so
I will show you various shortcuts in vs code to navigate your tests and production code last but not least we'll wrap up this section by talking about code coverage which is a metric that shows how much of our code is tested
this is a great introduction to unit testing so let's jump in and get
started so what exactly is unit testing well unit testing is a form of automat testing where we write code to check if our code works as expected here's an example imagine we have a function for calculating the monthly loan payment now
manually we would have to launch our application possibly login navigate to a particular page fill out a form submit it and then check if the result is calculated correctly as you can see this is pretty time consuming this is where
automated testing comes to the rescue we can write some code to directly call this function with various inputs and check if it Returns the correct result we execute this code using a program called a test Runner which displays test
results in the console or terminal window if a test passes we see a green tick otherwise we see a red cross using this technique we can run hundreds or even thousands of tests in just a few seconds clearly this is much faster than
manual testing through the user interface with automated testing our interface with automated testing our code base consists of two types of code the application code also known as production code and the test code or
tests once we have a suite of tests we can run them every time we make changes to our code and this brings us a bunch of benefits firstly unit tests help us identify and fix bugs early in the development process long before they
become nasty surprises in production there have been many studies that show that that the later we find and fix a bug in the development process the costlier it is for the business for example fixing a bug after deploying the
software can be up to five times more expensive than during the coding phase secondly unit testing helps us refactor our code with confidence refactoring means changing the structure of our code without changing its Behavior or
functionality for instance we can extract a few lines of code and put them into a separate function we're changing the structure of the code but not its functionality with unit tests every time we refactor our code we can run our
tests to quickly confirm if our code still behaves as expected thirdly writing unit tests encourages us to consider various edge cases and error conditions and this leads to more robust and reliable code and lastly unit tests
serve as documentation for how our functions should behave and this makes it easier for others to understand and maintain a project now despite these benefits we have developers with very strong opinions like our famous
superstar developer Mr John Smith who is skeptical about unit testing he proudly claims that in his 20 years of software engineering he's been writing bug free code without ever writing a single unit test on the other side of the spectrum
we have other developers like test Smith who are obsessed with writing test and say every line of your code should be covered by tests so who's right well in my opinion both of these viewpoints are extreme and can be costly for a business
having no unit test at all and relying solidly on manual testing can be very timeconsuming especially as our application grows in size and complexity on the other hand covering every line of code with tests can also be very
expensive we always have time and resource constraints so next time you encounter one of these folks with strong opinions don't get caught up in their debate instead be pragmatic and find a good balance that works for your project
keep in mind that every project is unique new projects with rapidly evolving requirements might not be the best candidate for extensive unit testing because as the requirements change some of your tests may break and
you end up spending more time fixing broken tests than delivering actual features however if your project is more established and certain features have stable requirements it's a good idea to write a suite of tests to ensure that at
least the critical modules continue to work as expected this way whenever you make changes to those modules you can run your tests to get immediate feedback if you have broken something or not in reality unit testing is an investment in
software quality like any investment it can be fruitful or go wrong if you skip writing tests entirely you will rely solely on manual testing and this will get increasingly costly over time on the other hand writing poor tests that
produce inaccurate results and fail to give you real feedback about your codes reliability is a waste of time so just like how you should wisely invest your money you should also use your time wisely when writing tests you should
write good tests that are maintainable robust and trustworthy and that's what I'm going to teach you in this course if your tests are not maintainable r and trustworthy they offer no value they get in the way and slow you down it's better
not to write them at all all right next we're going to talk about different we're going to talk about different types of
types of tests unit tests integration tests and endtoend tests so what are the differences well unit tests verify the correctness of individual units or
components of an application in isolation these units could be functions classes or even small modules these tests are incredibly useful for catching bugs early in the development process integration tests focus on verifying how
different units or components of your application work together as a whole they help you identify issues that might arise when combining different units such as data flow problems communication between modules and compatibility issues
between components and tests are the broadest type of tests focusing on testing the entire application as a whole they simulate real user interactions with the entire system from
the user interface down to the backend Services they're excellent for ensuring that our entire application works seamlessly from the user's perspective now a common question that I get is what types of tests should we write well the
classic recommendation is to have more unit tests than integration tests and more integration tests tests than endtoend tests this is referred to as the testing pyramid however this is just a suggestion it doesn't mean you should
follow it religiously because every application is different in some cases it may make more sense to have more integration tests or more endtoend tests there is no one siiz fits all in software engineering anyone who tells
you there is only one way to do something and that's the best way they're either selling you something or they haven't been around long enough so when designing a testing strategy for your application consider the complexity
of your application's code as well as your time and resources to come up with a suite of tests that give you the most value but there is one thing crucial you need to understand about the testing pyramid as we go up this pyramid in
other words as we test more units of our code together our tests will be slower but they will give us more confidence in the reliability of our application so end to1 tests give us the highest confidence but they're significantly
slower running them every time we change or refactor our code isn't always feasible this is where unit tests come into play unit tests are incredibly fast so we can run them every time we change or refactor our code to get immediate
feedback if you have broken something so all these types of test are valuable it's hard to determine which type has more value it's like debating what type of shoes is more valuable dress shoes or running shoes well it depends where you
want to go so don't listen to folks with strong opinions on social media saying things like unit tasks are a waste of time and they only write end to and tests well good for them anyway in this course our focus is entirely on unit
testing so you don't need to worry about integration and end to end tests at this where we will look at testing react applications we'll talk about applications we'll talk about integration
need a test Runner to execute our tests now this is where testing Frameworks come into the picture a testing framework is a set of tools for writing and running tests it typically includes a test runner for executing tests
assertion libraries to check if the code behaves as expected mocking tools to replace certain modules with Fakes simulating different scenarios test coverage tools for measuring how much of the code is tested and many other tools
now there are several testing Frameworks out there like just mocha Jasmine vest Cypress playwright and many many more all these Frameworks work more or less the same way so once you get the hang of one you can easily pick up other
Frameworks among these just is the most widely adopted and used in many projects however there is a little catch with just it's an older framework and its support for Eos script modules or n native JavaScript modules is still
experimental so setting up things can be a little bit awkward so in this course we'll be using Vest which is a new testing framework designed for modern JavaScript it has all the Fantastic
features of Gest as well as outof thee boox support for econ script modules typescript and jsx which is used in react plus its API is almost identical to just so everything you learn about vest in this course will will be
vest in this course will will be directly applicable to just as vest so I have opened our starter project in vs code now we need to open a
terminal window to install vest so on the top Under The View menu let's go to terminal look at the shortcut it's control and back control and back tick so here we're going to use npm to
install vest as a development dependency because we don't want to deploy our test tools with our application so we always install them as development dependencies so let's install
install vest lovely now we need to go to our package Json file and create a test script so here in the scripts object we script so here in the scripts object we add a new key value paent called test
and set it to vest now whenever we run npm test v test will execute our tests so if you go back to the terminal and run npm test or npm t v test will
execute our tests now currently we don't have any test files that is why we get this error in the next lesson we're going to create our first
test all right we're going to write our first test so here in the source folder we have a module called intro in this module we have all the code we're going to use in this section ction so here we have a function for getting the max of
two numbers pretty basic if a is greater than b it returns a otherwise if B is greater it returns B otherwise if they're equal it returns a I know this function this is deliberate once we
come back and refactor it into a more elegant implementation so to test this we're going to go in the root of our project next to the source project next to the source folder we create cre a new folder called
folder we create cre a new folder called test and here we create a test file for the intro module so we call it intro. test.js this is the pattern that vest or just looks for so vest by default pixel files that have test in their name and
of course this can be configured okay now in this file we're going to import a few functions from vest one of them is describe for creating a test Suite TW or
a group of related tests the other one is test for creating a test case there is also another function that does the same job it's called it we'll talk about that is expect so first we call the describe
function to create a test Suite or a group of related tests we give it two arguments the first argument is a string that is the name of our test Suite typically we use the name of the function or the unit under test in this
case Max the second argument is a function that will be called by our test runner in this case v test so here we pass an eror function now in this block
or in this test Suite we Define one or more test cases so we call test or it it doesn't matter it's a matter of personal preference now just like the describe function here we need two arguments the first argument is a string that
represents our test name so look here we want to test a scenario where a is greater than b so to name this test here we can pass a string like should return the first argument if it is greater now
look the reason Some people prefer to use the it function is because the test case reads like it should return the first argument if it's greater very clear so always pay great attention to naming your tests I've seen some people
naming their test like test one test two don't do that because over time it's not going to be clear what is the purpose of these tests so always treat your tests as first class citizens your test code is as important as your production or
is as important as your production or application code okay so here's a test name now the second argument should be a function that will be executed by our test runner in this case v test once again we pass an arrow function
now in this test we typically structure our test using the AAA pattern that is our test using the AAA pattern that is short for arrange act and assert this is a pattern that a lot of people follow when organizing their tests in the
arrange phase we set up our test environment including any necessary data or configurations in the ACT phase we perform the action we want to test and in the assert phase we check the outcome to ensure that it matches our expect
expectations let me give you a real example imagine we want to test that a example imagine we want to test that a TV can be turned off in the enrange part first we turn on the TV in the ACT part we press the power
button and in the assert part we verify that the TV is off okay now we can take this analogy and apply it to our tests so in the arrange part first we declare two variables or two constants we can call
variables or two constants we can call them A and B we set a to 2 and B to 1 now these are arbitrary values we could use 20 and 10 we could use 10 and 9 it doesn't matter what matters is that we want the first argument to be greater
now in the ACT phase we perform the action we want to test in this case we call the max function that is defined in this module so let's press enter the max function is imported on the top now we pass our arguments A and B get the
result and store it here now finally in the assert phase we verify that the result is correct to do that first we call the expect function of v test and by the way just has the same functions and they
work exactly the same way so we call expect and pass result now this returns an expectation object in this object we have a bunch of methods that start with is two these are called matchers we use these to verify expectations for example
we have to be to be called to be defined to be falsy to be greater than and so on as we go through the course you're going to get familiar with these matches in this lesson we're only going to use the to be matcher so we expect the result to
to be matcher so we expect the result to be two this is how we structure our test now we don't necessarily have to add these comments we can use a vertical line Breck to separate these sections this
way it's immediately visible that the first part is the range part the second part is the act part and so on now for simple cases we don't even have to have all these parts or all these faces we can combine them to make our test more
concise for example we don't need to declare these two constants because they're only used on this line so we can replace a and b with their literal values now we don't need the arrange part and similarly we can combine these
part and similarly we can combine these two lines into a single line so we two lines into a single line so we replace result with a call to the max function now our test has a single line of code so back in the terminal let's
run npm test or npm t all right we have one passing test beautiful and look the test name clearly identifies the scenario we're testing
now back in our test if I change this value to one now back in the terminal look now we have a failing test and the failure is happening on line six of this
failure is happening on line six of this module so the test expected one but it received two so back to our test let's change it back to two all right that was our first test case now we need two more test cases for scenarios where the
second argument is greater and also the scenario where our arguments are equal scenario where our arguments are equal so I'm going to duplicate these few lines so here's what we have so far in this test Suite we have two test cases
now let's change the name of the second test and here we say it should return the second argument if it's greater now let's swap the order of these arguments
back in the terminal now we have two passing tests in one test file and one passing tests in one test file and one more test case
I'm going to say it should return the first argument if arguments are equal so here we can pass one and one and expect the result to be one now take a look now
we have three passing tests and all these tests were executed in 8 milliseconds imagine if you wanted to test this function through the UI perhaps we have to do a few clicks perhaps we had to fill out a form
obviously we could never do this in 8 milliseconds right it would take several seconds but we are not done yet now that we have fully covered this function with tests let's refactor it with confidence so we're going to replace these three
lines with an expression like this return if a is greater than b return a return if a is greater than b return a otherwise return B back in the terminal look our tests are still passing this is the beauty of unit test they give us
immediate feedback if we have broken something during our refactorings however if you go back here and let's make it deliberate mistake let's return a in both cases now look one of our tests failed and that is this particular
test should return the second argument if it's greater so we expected to get two but we received one so let's go back and fix the arrow all right so that's that was our first test now as we go through the
course we're going to look at more complicated and real word examples all right here's your exercise in the same module we have a function
called fsus it's a very popular function that comes up in coding interviews so this function receives a number if the number is divisible by three and five it returns fizzbuzz if it's only divisible by three it returns Fizz if it's only
divisible by five it returns Buzz otherwise if the number is not divisible by three or five it returns that number as a string now as your exercise I want you to cover this function with tests now to give you a hint when writing test
for a function you should cover all the execution paths so here we have four execution paths here's the first one second third and fourth spend 5 to 10 minutes on this and then come back see my my
we have a test suite for the max function now we need to Define another function now we need to Define another suite for testing the fsbos function so we call describe and pass
where the argument is divisible by three and five so and five so it should return fiz buzz if argument is divisible by three and five I'm going a little bit faster because I'm assuming
you have done your exercise then we pass an aror function now once again here we don't need to have separate arrange act and assert faces we can combine all of them into a single line because our test is
very simple so we call fboss and and give it a number like fboss and and give it a number like 15 then we make an assertion and check to see if the result is Fizz
bu now back in the terminal beautiful we have four passing tests now to make sure that we're testing the right thing let's change this to change this to Fizz now we have one failing test lovely
so let's revert it back to Fizz boss this is a very simple and useful technique to ensure that you're testing the right thing because sometimes your testing the right thing or even the right function so always make a tiny
change to make sure that your test and production code are in sync another way to go about this is by modifying the production code so instead of changing the test code we can go back to the production code and create a bug so here
we can add an exclamation mark and now look we have one failing test so this verifies that our test code and production code are in sync in other words our test is actually testing this function because otherwise let me show
you an exaggerated example let's imagine instead of calling 2B we had a call to to be defined so we're checking that the value that is returned from this function is defined with this test now our test
passes even though we have a bug in our production code if we make any changes here our test still passes so this shows that we are not testing the right thing this is what we call a false positive so our test always passes giving us an
illusion that our code works we can also have false negatives tests that always fail even though there's no bug in our production code so this technique is very useful to prevent false positives and false negatives you want to make
sure that our test code and production code are inan think or in other words code are inan think or in other words we're testing the right thing so let me bring back the 2B match and compare the result
with fiz Buzz okay now we have a failing test Buzz okay now we have a failing test lovely so let's go back and fix the
test case now let's move on to the second test case so I'm going to duplicate these few lines this time we say that our function this time we say that our function should return fiz if argument is only
divisible by three so we can pass three or 6 or 9 it three so we can pass three or 6 or 9 it doesn't really matter let's compare it with fizz we have one passing test now to
make sure that we're testing the right thing again we can go back to our production code and make a tiny change here there you go now we have a failing test so our test and production code are in
so our test and production code are in sync now we need two more test cases so let's duplicate this test and change the name to it should return buzz if name to it should return buzz if argument is only divisible by five so
here we pass Five and compare the result with with Buzz one more passing test and the last test case it should return argument as a string if it's not
argument as a string if it's not divisible by three or and here we expect to get one as a string seven passing test but if you
pass one as a number now we have a failing test okay so let's revert it back beautiful we're done with this lesson next we're going to talk about test driven [Music]
development there are two ways to write tests code first or test first code first is what we have been doing so far we write the application code first and then we cover it with tests test first is the opposite we start with tests and
then we produce the application code this approach is also called test driven development or tdd TD CD is a way of building software it follows a simple effective three-step cycle we start by writing a failing test and then we write
just enough code to make the test pass then if necessary we refactor our code while ensuring that all tests still pass and then we repeat let's see this in action so let's imagine we want to create a function for calculating the
average of values in an array so we start by writing a failing test so back to our test file first we create a new test Suite let's call this calculate
case for an empty array let's say that if we pass an empty array to this function we expect to get not a number so it should return not a number if
so it should return not a number if given an empty function so back to to our intro module we Define a function called calculate
we Define a function called calculate average that takes an area of numbers and then export it from this module so we're not going to implement this yet we just have the Declaration of the function now back to our test so we call
function now back to our test so we call calculate average and give it an empty calculate average and give it an empty array and then expect the result to be not a number okay back in the terminal look we
number okay back in the terminal look we have a failing test because we expected not a number but we received undefined because in JavaScript all functions by default return undefined unless we explicitly return a value so to make
this test pass we go back to our intro module and write the simplest module and write the simplest implementation possible so we return not implementation possible so we return not a number now we have one passing test
beautiful that was one cycle now we need to repeat this with other test cases so to repeat this with other test cases so as our second test
and give it an array with a single element so we can change the test name element so we can change the test name to should calculate the average of an to should calculate the average of an array with a single element so we call
it and give it an array with just one and expect the result to be one now look again we have a failing test so we have to write just SE of code to make this
test pass so back to the intro module now we can say if numbers the length now we can say if numbers the length equals zero then we return another equals zero then we return another number otherwise we return numbers of
zero obviously this logic is still immature but we're going to enhance it with more test cases so back in the terminal now we have nine passing test so we completed one more cycle now let's write another test case
for an array with two elements so back to our test file let's duplicate this to our test file let's duplicate this test case and say it should calculate the average of an array with two elements so if we pass one and
two we expect the average to be 1 and half now look again one failing test so we go back to our intro module and write the simple
logic here we can use a for Loop to iterate over this array and calculate the total of all values or we can use the reduce method so here we call numbers do reduce and give it an arrow function
this function should have two parameters the first parameter is an accumulator or a variable that con contains the total value we can call it total or sum that's better the second parameter holds the current value one value at a time in
current value one value at a time in this array so we can call it current now in the body of this function we simply add current to sum so we return sum plus current so this function is the first argument to the reduce method now as the
second argument we need to provide the initial value for the sum so we we initialize it to zero now with this we get the sum of all numbers in this array
get the sum of all numbers in this array and finally we can divide sum by and finally we can divide sum by numbers. length now back in the terminal all our tests are passing lovely so let's write one more test case this time
let's write one more test case this time we want to pass an array with three elements so if you pass 1 2 and three the average should be to now look
all right all our tests are passing so this was tdd in action we started by writing tests and as a result we produced this function now the beautiful thing about tdd is that it produces production code that is 100% covered by
tests so here we don't have any execution paths that we haven't tested the current implementation of this function is fully covered by tests if the implementation is not complete yet we can add other test cases to drive the
development the other great thing about tdd is that it prevents us from over engineering because our focus is on rating the simplest logic to make the tests pass and we can always refactor and refine our implementation what
matters is that we are not over engineering ahead of time so these are the benefits of tddd but in practice tdd can be difficult especially for new Learners so in this course our Focus will be on the code first approach but
as you learn unit testing you can challenge yourself and start exploring tdd first it might be difficult especially in more complex applications but trust me over time with practice it gets easier and easier now I just want
to clarify something here tdd as a philosophy is great but it doesn't mean that you should always write tests using this approach I know that there are some they say you're not a developer if you don't use tdd but again this is one of
those extremely radical viewpoints if you don't like tdd or if you prefer to write tests after the production code that is perfectly fine again there is no one-size fitall in software engineering every project every team is different so
always use the approach that works for you and your to implement the factorial function using tdd we have all studied factorial
at school in math now to refresh your memory the factorial of an number is the product of all positive numbers from one to that number here are a few examples to that number here are a few examples so factorial of 0 is 1 factorial of 1 is
so factorial of 0 is 1 factorial of 1 is 1 factorial of 2 is 2 * 1 factorial of 3 1 factorial of 2 is 2 * 1 factorial of 3 is 3 * 2 * 1 so write a test case for each of these scenarios and then implement the factorial
function all right so we start start by creating a new test Suite called factorial first we write a test case for the factorial of zero so should return
the factorial of zero so should return one if given factorial function so back to our intro module we export a function called
factorial that takes a number and we leave out the that takes a number and we leave out the implementation now back to our test we call factorial and give it zero and then we
expect the result to be one back in the terminal obviously we have a failing test so to make this test pass we go back to our intro module and
return one all right our test is passing now one all right our test is passing now the second test case so we duplicate this and change the test name to it should return one if given
so let's add another test case should return case should return two if given
need a bit of logic we can check if n equals 0 or 1 then we return one otherwise we can do a trick we can just return two we hard Cod this value and our tests are
still passing so what I want to emphasize here is that we want to write just a little bit of code to make our test pass we want to do baby steps we write a lot of logic because that can
lead to over engineering ing so our tests are still passing so let's add another test case should return six if given
case should return six if given three so factorial of three should be three so factorial of three should be six now one of our tests is failing so we go back to our factorial function and this is where we make another step so
instead of hard coding two or six we implement the actual logic here we can implement the actual logic here we can use recursion so we multiply n by factorial of n -1 all our tests are passing lovely
let's add one more test case what if we pass case what if we pass four factorial of four should be
passing beautiful now what if we pass a negative number well that's one of the areas that is is debatable but we can say that factorial of negative numbers say that factorial of negative numbers is undefined so we write another test
case here and say it should return here and say it should return undefined if given a negative number so
undefined if given a negative number so we pass -1 and expect the result to be undefined now we also have a separate matcher function here that is to be un matcher function here that is to be un defined we can also use this back to the
terminal one of our tests is failing so back to our factorial function let's add another if statement and say if n is less than zero then return
lovely now I just want to clarify something here as part of writing tests test first approach we don't want to test against all possible numbers in the world because that is is Not Practical so we don't want to test a factorial
numbers we want to have enough numbers in different ranges like zero positive different test cases for different scenarios that is
sufficient all right what's next well if you want to learn more I have a comprehensive JavaScript unit testing course on my website what you have watched is the first 40 minutes the full course is 4 hours long and goes Way
Beyond the basics we'll talk talk about various techniques for writing effective tests that are robust maintainable and trustworthy we'll talk about positive and negative testing boundary testing writing parameterized tests testing
asynchronous code and using marks and spies to isolate code during tests we'll also have a section on improving code quality using static analysis tools we'll talk about formatting code with prier linting it with es lint catching
type errors with typescript and automating code quality checks with Husky so by the end of the course you will have a strong foundation in unit testing and we'll be ready to learn about testing frontend applications like
react the full course is packed with a ton of exercises so you can practice what you will learn and the best part is that it comes with a certificate of completion and a 30-day money back guarantee so if you're not satisfied
interested use the link below this video to enroll I hope to see you in the to enroll I hope to see you in the course thank you and have a great day
[Applause] up
