Introduction To Testing In JavaScript With Jest
Summary
TLDRIn this informative tutorial, Kyle from Web Dev Simplified introduces viewers to the fundamentals of JavaScript testing using the Jest library. He demonstrates how to set up a testing environment, write unit tests for simple functions like sum, subtract, and array cloning, and utilize Jest's matchers to ensure code correctness. The video also highlights the importance of testing in development, its role in identifying bugs during code changes, and the confidence it provides when making large-scale updates to complex applications.
Takeaways
- π Testing in JavaScript is a crucial skill for developers that can set them apart in the job market.
- π The video introduces 'jest', a popular JavaScript testing library, as an essential tool for testing.
- π The tutorial starts with the basics of setting up 'jest' by initializing 'package.json' and installing it as a development dependency.
- π οΈ It demonstrates how to write tests for simple JavaScript functions like adding, subtracting numbers, and duplicating arrays.
- π The script explains the process of creating test files with the naming convention of appending '.test' to the original file name.
- π§ The importance of using 'expect' and 'toBe' in 'jest' for asserting that function outputs match expected results is highlighted.
- π The video clarifies the difference between 'toBe' (for strict equality) and 'toEqual' (for deep equality) in testing arrays.
- π 'jest' offers code coverage analysis, which is shown to ensure that all parts of the code are being tested.
- π The script emphasizes the value of unit testing, which focuses on testing individual components or functions in isolation.
- π‘οΈ Tests provide confidence when making changes to the code, as they help identify any breaks or issues that arise from modifications.
- π The video concludes by advocating for the practice of testing as a means to ensure code quality and simplify the development process.
Q & A
What is the main topic of the video?
-The main topic of the video is testing in JavaScript, focusing on how to get started with testing using the Jest library.
Why is testing an important skill for developers?
-Testing is an important skill for developers because it helps set them apart from others who don't know testing, and it gives them an advantage when applying for jobs.
What does the instructor suggest for simplifying web development?
-The instructor suggests using the Jest library for testing in JavaScript as a way to simplify web development and ensure code quality.
What are the JavaScript files created for the purpose of this video?
-The JavaScript files created for this video are simple functions for adding two numbers, subtracting two numbers, and duplicating an array.
What is the spread operator in JavaScript and what does it do?
-The spread operator in JavaScript is a syntax that allows the expansion of elements from an iterable (like an array) into individual elements, and it is used for duplicating an array in the video.
How do you install the Jest library for testing in JavaScript?
-You install the Jest library by running 'npm install --save-dev jest', which adds Jest as a development dependency.
What is the purpose of the 'test' script in the package.json file?
-The 'test' script in the package.json file is used to run the Jest testing framework with the command 'npm test'.
How do you create a test file for a JavaScript function?
-To create a test file, you name it the same as the file you want to test with '.test' appended to the filename and '.js' as the extension.
What is the 'expect' function used for in Jest tests?
-The 'expect' function in Jest is used to specify the expected outcome of a test, allowing for assertions such as equality or matching certain conditions.
What does the 'toBe' matcher in Jest do?
-The 'toBe' matcher in Jest checks for strict equality, ensuring that the expected value and the actual value are identical in both value and reference.
Why is it important to test individual functions in unit testing?
-Testing individual functions in unit testing is important because it isolates each part of the code, making it easier to identify and fix issues when a test fails.
How can running tests help with making changes to the code?
-Running tests helps with making changes to the code by verifying that the changes did not break any existing functionality, providing immediate feedback if something is wrong.
What is the purpose of code coverage in testing?
-The purpose of code coverage in testing is to measure how much of the codebase is executed during the tests, ensuring that all parts of the code are tested and reducing the risk of undetected issues.
How does testing provide confidence when making large changes to an application?
-Testing provides confidence when making large changes to an application by quickly identifying any breaks or issues, allowing developers to ensure that the application remains stable and functional after changes.
What is the benefit of having a test suite for a large application?
-A test suite for a large application allows for quick and automated testing of the entire codebase, reducing the need for time-consuming manual testing and providing assurance that changes do not introduce new issues.
Outlines
π» Introduction to JavaScript Testing with Jest
The video begins by emphasizing the importance of testing in JavaScript, highlighting it as a crucial skill for developers that can give them an edge in the job market. The host, Kyle, introduces the topic and his intention to simplify web development for viewers. He presents a few simple JavaScript files with basic functions like adding and subtracting numbers and duplicating arrays. The focus then shifts to using the Jest library for testing, starting with initializing a project with 'npm init' and installing Jest as a development dependency. The video guides viewers on setting up the testing script to run tests using Jest and creating the first test for the sum function. It explains how to write a test using the 'test' function in Jest, asserting the expected outcome with 'expect'.
π Deep Dive into Writing Tests and Understanding Test Results
This section delves deeper into the process of writing tests for different functions, such as cloning an array and subtracting numbers. It clarifies the difference between 'toBe' and 'toEqual' in Jest, explaining object equality and value equality. The video demonstrates how to create a test for the 'cloneArray' function, emphasizing the importance of ensuring that the cloned array is a duplicate and not a reference to the original. It also shows how to test the 'subtract' function and the importance of accurate naming in test cases. The host introduces code coverage as a way to measure how much of the code is being tested, using Jest's coverage feature to generate a report and an HTML file that visually represents which parts of the code are covered by tests.
π The Importance of Testing and Unit Testing Philosophy
The final part of the video discusses the broader significance of testing in software development. It uses a scenario where a change in the 'sum' function leads to a test failure, illustrating how tests can catch bugs early. The video explains the concept of unit testing, focusing on testing individual components of code in isolation. It argues for the simplicity and effectiveness of unit tests in identifying specific failures within small code units. The host also touches on the psychological benefits of tests, providing developers with confidence to make changes knowing that their test suite will catch any issues. The video concludes with a call to action for viewers to engage with more testing content and to provide feedback on creating further videos on the topic.
Mindmap
Keywords
π‘Testing
π‘JavaScript
π‘Jest
π‘npm
π‘spread operator
π‘unit testing
π‘expect
π‘test coverage
π‘assertions
π‘refactoring
Highlights
Introduction to the importance of testing in JavaScript for developers.
Using testing to set oneself apart in the job market.
Introduction to the 'jest' library for JavaScript testing.
Explanation of how to initialize a project for testing with 'npm init'.
Installation of 'jest' as a development dependency.
Configuring the 'package.json' to include a test script.
Creating test files by appending '.test' to the original file name.
Importing functions to be tested in the test files.
Writing the first test using 'test' function and 'expect'.
Demonstration of a passing test for the 'sum' function.
Explanation of 'expect' syntax and available matchers.
Testing the 'cloneArray' function for deep equality.
Difference between 'toBe' and 'toEqual' in testing.
Ensuring the 'cloneArray' function creates a distinct copy.
Creating tests for the 'subtract' function similar to 'sum'.
Running tests and understanding test results.
Using '--coverage' flag to check code coverage.
Importance of testing in catching bugs when modifying code.
Concept of unit testing and its benefits in isolating issues.
Building confidence in code changes through testing.
Encouragement to explore more on testing and request for feedback.
Transcripts
hello everyone in today's video I'm
going to be covering testing in
JavaScript which is one of the most
important skills you can know as a
developer it's something a lot of people
don't teach or focus on but if you know
testing it's gonna set you apart from
every other developer that doesn't know
testing and give you that extra leg up
when you're applying for jobs so in
today's video I'm gonna show you the
very basics of how to get started with
testing in JavaScript using chests
welcome back to web dev simplified my
name is Kyle and my job is to simplify
the web for you so you can start
building your dream projects quicker and
better and if that sounds interesting
make sure you subscribe to my channel
for more videos just like this one and
to get started in this video I have
something a little bit different than
usual I have a few files already created
and these are very simple JavaScript
files all they do is to find a very
simple function and then export that
function for us in our case we have a
function that adds two numbers we have a
function that subtracts two numbers and
we have a function that duplicates an
array and if you aren't familiar with
this spread operator syntax I have an
entire video that covers it links in the
cards and the description down below if
you're interested but essentially all
this is doing is duplicating the array
and creating a brand new array from the
current array that were given and as I
mentioned at the beginning of this video
we're going to be talking about testing
and how to test in JavaScript and the
easiest way to do that in my opinion is
to use the library called gest which is
an incredibly popular and well-built
testing library inside of javascript so
in order to start this all we need to do
is run NPM an it hash that's why to it
that way it will initialize with all the
default values and this gives us our
starting point package.json next we need
to install so we're gonna NPM - - save
dev and we want to install just this is
going to be our testing library and the
reason we're saving it as a development
dependency is because we only use this
testing library in development to make
sure everything runs now that that is
done downloading we can come in here
where we have our test script and we can
just change this by typing in jest and
essentially now when we run NPM test
it's going to actually run just and run
our tests but of course right now we
don't have any tests so this is just
going to fail so to get started creating
your very first test all you need to do
is create a new file give it the exact
same name as the file you want to test
in our case we'll test some and then you
just say dot test and then j/s so
essentially you just take the same file
name add test to the end of it and make
sure the Dodge is stays at the very end
now inside of this file all we need to
do is import our sum function because as
you remember here we're exporting a
function called sum so we're going to
import that function by just saying in
here we want to require dot slash sum
this is going to import this sum
function and then we can actually write
a test for this so what we want to do is
to test to make sure our sum function
works so essentially we want to test
that when we give it two parameters for
example one plus two we want to test to
make sure that that is equal to three
and in order to write a test with just
we use this function called
test and the very first parameter to
this test function is just a string of
what the test is doing so in our case we
can just say that it properly adds two
numbers you just write what you want to
test inside of that string because this
will actually show up inside of the
console when we run this test the second
thing is going to be a function and this
function is what gets called to run your
test so we have a test which is going to
properly add two numbers and then it
calls this function and inside this
function we need to make sure that our
expected result happens and in order to
do that normally in JavaScript you maybe
would put like an if you could say if
sum of 1 and 2 is equal to 3 then you
want to run some code inside of here
otherwise if it doesn't work you want to
throw some kind of error maybe and that
would be how you would do this as normal
JavaScript but this is kind of bulky and
hard to use so we'll just they actually
have functions built-in that allow you
to do this testing and those test
functions are called expect just like
that so what we're saying is we expect
something to equal something else so we
are expecting sum of one and two and we
want this to be 3 so we could just say
to be and we pass in 3 now if we save
that and run this you should see that
our test you're going to run and they
are going to pass
as you can see it's running this test
right now and you can see it's ran all
of our tests and they're passed let's
just expand this up so we can see it
easier and you can see that it ran
properly adds two numbers in two
milliseconds and it passed and it says
everything is working fine and it took
about two seconds to run everything
let's bring that back down and I'm going
to go into this syntax a little bit more
because this looks really confusing I
guarantee so let's break this out so
it's a little bit easier to read and
know exactly what's going on the first
section we have is expect and expect
takes anything that we want and we're
saying we expect whatever is inside of
this section to do something related to
the other section and there's a lot of
functions we can use for example to be
to equal not to be to be Nold to be
undefined and so on there's quite a lot
of different matches that you could use
in this case but for our simple example
what we're doing is checking that one
plus two is the same as three and in our
case that passed and ran correctly
now let's go over to our clone array
function here and what we want to do is
we want to test to make sure our array
is the same we just want to make sure
that we created a duplicate array that
is exactly the same so let's create that
new file clone array SJS and inside of
here again we need to import our clone
array function so we can just do that
require oops require dot slash clone
array and then inside of here all we
need to do is do that test if we want to
say it properly
clones array and in here we can just run
that we want to say expect clone array
and we want to create an array first so
we're just going to say Const array it's
going to be equal to just two array with
some random numbers in it so we want to
expect this is going to be our array and
we're actually going to get a failure
when we do this so let's just run this
test real quick and this is actually the
difference between to be and to equal so
once we get this we're going to scroll
up so we can see our error and as you
can see right here it says what did
expect receive to be expected object is
equality if it should pass with deep
equality replace to be with too strict
equal and it says expected one two three
and it says received serializes to the
same string so this is kind of saying is
it saying these objects
look to be exactly the same the value
seems to be the same but there are
actually different places in memory
because remember I said clone array this
is actually creating a brand new array
with all of the same values so now we
have two arrays that are both
referencing they both have the same
value but they're referenced by
different memory addresses and this
sounds a little bit confusing but I have
an entire video on pass by value and
pass by reference that I break this down
in so you can check that out linked in
the cards and the description below but
essentially what we need to use is
something called to equal instead now if
we run our test this is actually going
to pass because our arrays both have the
same structure they're both 1 2 3 and as
you can see they both passed they just
don't have the same memory address so we
can use a second test where we can say -
we want this to be not to be array and
we can run that and the reason we're
testing this is we want to make sure our
clone array is actually making a copy
and then it's not just the exact same
array and as you can see that passed so
we made sure our array is the same right
1 2 3 and we also made sure that it
created a clone instead of just
returning the exact same array it
created a clone of that array a little
bit confusing but as I mentioned you can
check out that video and it will break
down pass by reference and pass by value
for you really easily now one last thing
we need to do is let's create a test for
our subtract test Jas and inside of here
I'm just going to copy our sum test
because it's going to be very similar we
want to make sure we import our subtract
method and we want to do that this is
properly subtracting two numbers and of
course we need this to be negative 1
because 1 minus 2 is negative 1 let's
run that and agur of course we should
say here that all of our tests are going
to pass as soon as this finishes and as
you can see we're getting an error and
that's just because this needs to be
subtract instead of sum and now when we
run this test we should get everything
to pass again which is going to be
perfect and just a second there we go
everything passed but it's kind of hard
to tell what parts of our code are
tested right now it just says that our
tests passed but how do we know which
functions got tested which lines got
tested and this is actually really easy
to do we just need to pass in the - -
coverage property to our just test now
if we save this
and run our test again it's actually
going to make note of every single line
that gets ran every single function that
gets ran and make sure our code is
tested 100% and as you can see here it
says that all of our files have all the
statements branches functions and lines
tested 100% and it even generates up
here an HTML file index.html if we open
this up I bring this over you can see
that it actually has all of our code
being tested 100% but if for some reason
instead of our sum we had a separate
function let's just say we had a
function called helper and this function
is just going to do something let's just
say it logs out helper now if we run our
test we are actually test this function
nowhere in our test are we running this
helper function ever so you're going to
see down here when this finishes that we
have some of our code not being tested
and we can just open this back up so we
can actually see and as you can see we
get generated out that only 66% of our
statements are tested 50% of our
functions and if we click on it you can
see in red is all the sections that are
not being tested which makes it really
easy to note if we're actually testing
everything that we want to test
now before I died of any further I want
to step back a little bit and talk about
testing as a whole why it's important
and how you can actually go about doing
it in an easy manner because I've shown
you how to actually write your tests for
your functions by using the text test
keyword and the expect as well as to be
two equal to other things I don't know
what you want to test and that's all
great but how do you know you're writing
good test and why do you even bother
writing tests well let's say for example
we want to change our sum KS and we're
coming in here we're making a bunch of
changes we're writing all this new code
and somewhere along the lines if we
accidentally change this B to a so now
our code is saying return a plus a
obviously a plus a is not going to be
what we want so now when we run our test
again we're gonna get a failure so this
is a way for us to be able to change our
code and know that everything is working
properly if our test passed or if in
this case our tests fail we know
somewhere along the lines we broke our
sum function because our TAS are tests
for properly adding two numbers is now
failing so what we do is we're going to
go back look at our sum function to
realize oh whoops we changed our
to a B or a B to an A let's change it
back to the beef run our test and this
is just a really great way to verify
your program does what you want it to do
and in all of these tests I'm doing
what's called the unit testing and unit
testing is when you test the smallest
unit of your code in our case this is
just a single function we want to test
only one single thing at a time for
example I could write a fancy big test
that could test some it could test clone
over a Anika test subtract all at once
and do all this crazy testing but that
would be a lot harder to write and it
wouldn't really tell you that much if
that test breaks is your problem in sum
is it in clone array is it in subtract
is it even somewhere else with unit
tests what you're doing is you're
breaking your code down into really
really small components essentially
small units and you're testing these
individual units so now you know if your
test for a single unit failed that that
single unit is broken and you know
exactly where to go to fix it also it
allows you to write really small tests
because you're only testing a small part
of your code so you only need to make
sure inputs and outputs for that very
small section of code are what you
expect so it makes testing really easy
because your tests are just super simple
like this obviously in your use case
your test might be slightly more complex
than just one plus two but it's still
going to be incredibly simple another
really important thing about tests is
that they give you confidence let's say
our application is hundreds of thousands
and millions of lines of code long and
we want to make some really large change
to our code we want to refactor it so it
does something slightly differently that
it didn't do before and it's doing a lot
of different changes we're touching a
lot of different files and it's hard to
manually test your application maybe
it's a huge website with thousands of
webpages and manually testing all of
that is impossible it'll take hundreds
of hours to manually test so you can't
manually test after every change but you
have your test suite with all these
different individual tests and all you
need to do is just run it npm test and
it'll tell you if anything inside of
your code is broken now obviously it's
hard to make your test 100% cover every
single type of edge case that you could
have but the goal is to make your test
as bulletproof as possible so almost
every single thing that can happen in
your application will be tested so you
know that if your test suite passes
you know that your application is good
to roll out to production and you don't
have to do lengthy manual testing you
only need to do a small amount of manual
testing just to verify for yourself that
everything works but other than that you
can just push it up to production as
long as your tests actually pass so
there is a really quick overview of unit
testing with chest if you enjoyed that
video make sure you check out my other
videos linked over here and subscribe to
my channel for more videos just like
this I would love to make more testing
related videos so if that sounds
interesting to you make sure let me know
down in the comments below thank you
very much for watching and have a good
day
Browse More Related Video
How To Create And Publish Your First NPM Package
ISTQB FOUNDATION 4.0 | Tutorial 36 | Value of White Box Test Techniques | CTFL Tutorials | TM SQUARE
Introduction to HTML | An HTML5 Tutorial for Beginners
Learn JavaScript Event Listeners In 18 Minutes
Software Testing Explained in 100 Seconds
Learn Closures In 7 Minutes
5.0 / 5 (0 votes)