Unit Testing (Vitest) Tutorial #2 - Writing Your First Test

Net Ninja · Beginner ·🛠️ AI Tools & Apps ·7mo ago

Key Takeaways

This video tutorial series covers unit testing with Vitest, including setup and writing effective unit tests for code, with a focus on using Vitest to test a function called longest string.

Full Transcript

All right, then. So, we've got Vest installed now. And next, we want to start writing some tests. So, I've already created this new file called examples.js. And inside that, I've made a function called longest string, which takes in two arguments, string one and string two. And all this function does is check if the length of string 2 is greater than the length of string one. If it is, then it returns that string, string two. Otherwise, it returns string one down here. So in other words, it returns the longest string and when they're equal in length, it just returns string one. So this function then takes in some input and returns an output. And now I want to test the function against different values for the inputs. To do this, we're going to make a new folder called tests, which is where we're going to create all of our test files. Now, you don't have to make this folder. You can place your test files somewhere else if you want to, but I like to keep my test files in a separate dedicated folder where possible. So then we're going to make a new test file to test this function. And we'll call that file the same name as the file we already have or module that we already have which is going to be called example. And then we add the test.js extension. And any test files that you make should have this test part within the file name because that's what vest will look for. All right. So now we have this file. We can write a new test inside it. But before we write anything, I want to quickly go over the basic anatomy of a test and talk about some common testing terminology. So when we start writing unit tests, we usually begin by creating something called a test suite, which is just a group of related tests for a single function, module, or feature. And we use test suites to organize those related tests together in one place. So we make a new test suite by using the describe function, which comes from the vest package that we installed. And as the first argument to that describe function, we pass a string to describe the suite or to describe what we're testing. For example, that could be a function name or the module name or even the module name and then the function name. For example, examples.loongest string. The second argument to that describe function is a function itself. And it's inside this function that we create all the individual tests which test different things to do with this longest string function. Now we can do that using another V test function called it. And this also takes in two arguments. The first one again is a string. This time describing the individual thing that we want to test. And the reason this function is called it by the way is because it kind of starts a sentence or statement, right? For example, it returns the longest string. And the second argument again is a function which will contain all of the testing logic this time. And it runs this when the test is executed. And in testing terminology, this test block right here is called a test case because we're testing one single case or behavior of the longest string function or whatever other function we might be testing. Now, inside this function, we typically run the function that we're testing and pass it some input values which we can then store in a variable. And then we'd make assertions about that return value by using another vest function called expect. So we'd run the expect function and pass in the value we want to test like the return value from the function call we stored earlier and then we chain on one of V tests matcher methods like to be to describe what we'd expect the value to be. In this case we'd expect it to be the longer of the two strings that we passed into the function. So this line right here is called an assertion because we're asserting a certain behavior or outcome from the function. And those three things, the suite, the test cases, and the assertions are the backbone of most unit tests that we write. So now let's take all this and try making a few tests in our project. So then we want to make a new test suite in this file where we can write test cases for the longest string function. And to do that, we need to import the describe function from vest. So let's do that at the top of the file by saying import and then curly braces. And we want the describe function. Okay. And that comes from the vest package. So now we can use that function down in this file to make a new test suite. And we can invoke that function as well. So remember the first argument is a string to describe what function or module we're testing. And I'm going to call this examples.longest string because we're testing the longest string function from the examples file. Okay. Next up, we need to pass in a function as the second argument where we can then write all of our individual test cases. So then let's do that. And then next to write those test cases, we need to import a second V test function which is called it. So let's do that up at the top. And now down inside this function, we can make a new test case by invoking that it function and describing what particular outcome we want to test. For now, let's use that basic example which was it returns the longest string. Okay. So, as a second argument, we need to pass in a function to put all of the testing logic inside of. Now, for this test, we need to invoke the longest string function, right? And pass in two strings as arguments. So let's first of all import the longest string function at the top of the file by saying import and then again curly braces and then the name of the function which in this case is just longest string and that comes from dot dot forward slash then into the source folder and then forward slash and the name of the file which is examples. All right and now we have that function we can use it down inside the test case. So let's do that by making a new constant called longest to store the return value. And then we'll set that equal to longest string and invoke the function. And then we need to pass in two strings. So the first one could be Pikachu and then the second one could be Snorlax. So from these two strings, we would expect the first one Pikachu to be returned and stored in this constant, right? Because it's the longest one out of the two. And that's what this function is meant to do. Return the longest of the two strings. So let's actually test that now by making an assertion. To do that, we need to import that third V test function called expect. So let's do that up here. And then back down in the test, we can invoke the function. And we can pass in the return value longest as an argument. Then after that, we need to tack on one of Vest's matcher methods. And the one we're going to use is called to be to assert what we'd expect the value of that variable to be, which in this case would be Pikachu. And that's it. We have now made our very first test. And we could run the test script now to see if this test passes. So let's open the terminal to do that. And we're going to type npm run test and then hit enter. Now once we do that, vest is going to run. It's going to look for any test files in our project. and it's going to execute any tests inside those files and then spit out the results down here. So we can see that this single test that we wrote now passes. All right. So V test is still going to carry on running in the background now waiting for any changes to the test files. And now if we make and save any changes to them then it's going to rerun the test automatically for us which is nice. So if I change this expected value from Pikachu to Snorlax now and then save the file, VEST is going to run the test again automatically and this time we should see that the test fails and it also tells us exactly which test failed. So then let's change that value back to Pikachu and save the file again to make sure that the test is passing as it should do. All right, so that's it. We've now created our first unit test which tests the basic functionality of the longest string function. But there's still more cases for this function that we can test like if it returns the first string if the two given strings are the same length or does it take whites space in the strings into account. So let's try making a couple more test cases now in this same test suite. All right. So let's come down here now and create another test case which we do by using this it function again. And then for the first argument, we'll pass the string returns the first string when both are of equal length. So if we go back to the function, we can see that string two is only returned if string 2 length is greater than string one length. But if they're both the same, it should return string one. So then let's pass in this function as a second argument. And inside this function, I'm actually just going to copy this thing right here and paste it down below. And for the first argument, I will this time pass in ditto. And for the second one, we'll pass in Pidgey. So they're both five characters in length, right? And because we return string one, where they're both the same length, then we should get ditto back, right? So let's make an assertion down here by saying expect and we'll pass in the longest again. And then we'll say that should be ditto. Like so. Now I'm going to save this file and open up the terminal. And now we can see two tests have passes including this one right here. Now just one thing I want to show you. We don't always have to have a separate line for this function call. If this is just returning a simple value like a string, then we can just invoke that directly inside this expect call like this. And since it just returns a value when it runs, we're just expecting the return value of this to be ditto. So that is exactly the same thing. So if I save this again and open the terminal, we should see everything still works. All right. So let's do another example. I'm going to make a new test case down here by saying it and invoking this again. And this time we will say it handles empty strings. So what happens when one or both of the arguments are empty strings? So let's create a function here to write the assertion in. And what I'm going to do is the same as this thing right here where we invoke the function directly inside the expect function. So let's say first of all expect and then we'll say longest string and we'll pass in an empty string for the first argument and then we'll pass in Mario for the second argument. Now what would we expect this return value to be? Well, there's still two strings, right? So I would say it should still return this one right here, Mario. So we'll say expect that to be Mario. Now before we run this test, I'm going to duplicate this a couple of times and just change these values. Then we'll run them all together. So for this second one, we'll say the first string is Luigi and then the second string can be empty. And then for the third one, we'll test when both strings are empty. All right, so let's save this. Oh, in fact, we need to change these values. So that second one should be Luigi. And then this third one should just be the empty string. Right? They're both empty strings and they're both the same length. And we return the first one when they're both the same length. So let's save that now and open the terminal. Hopefully they're all going to pass. And we can see yeah handles empty strings. All of those assertions pass. All right. So I'm going to close this and do one more example. So let's come down here and say it again. And this time we'll say it ignores leading or trailing whites space. So by that I cannot spell this white space. So what I mean by this is if there was for example a load of white space inside this string right here even though it might technically be a longer string than this I would still want it to ignore this white space and return this one because this is the actual word right? I don't want just whites space to be classed as longer. So I want the function to ignore that whites space. So then let's pass in a function for the second argument. And inside here we can say expect and we'll say longest string and invoke that. And then we'll do a string some white space. Then we'll say ash some more whites space. Um and then we'll do a second argument. So this second one can just be misty. Now, technically, because we've got a load of spaces in here, this might be more characters, but I'd want it to return that. So, I'd expect the return to be misty, right? So, let's save this now and see what happens. I'm going to open up the terminal, and we see a fail. So, it says right here that it expected ash to be missed in this test right here. So, it's actually returning ash. It received this, but it expected missed it. And that's because the function at the moment is treating these whites space characters as actual characters. So this is a chance now when you create a test that doesn't work for you to go back into the test and have a look why it doesn't work. Well, what we'd need to do for this to work is trim both of these strings. So we can say string 2.trim. And what that does is get rid of any white space at the start or end of the string. And we're going to do the same for string one. So say string one.trim trim.length. And now we're getting rid of all that white space and we're just looking at the two strings themselves. So if we open the terminal again, it should have rerun. And now we can see this test passes. Awesome. Okay then. So we've made a few different test cases now. And there's just one more thing I want to show you in this lesson. And that is another function we can use called test. And this function is just an alias of the it function. It does exactly the same thing. But sometimes you'll see other developers using this function test instead of the it function. It's all down to personal preference. But I want to show you that they do exactly the same thing. So make sure we import that test function up at the top of the file. And then just replace one of the it function calls with the test function. And once you've done that, we can save the file, which should trigger V test to run the test again automatically. And in the terminal, we should see that everything still passes the same as it did before. All right. Okay. So now we know how to write some simple tests. And in the next lesson, I want to talk a little bit more about matcher methods like this to be one right here.

Original Description

In this Unit Testing tutorial series, you'll learn how to setup Vitest in a project, and use it to write effective unit tests for your code. 🍿👇 Get the Testing Bundle (inc Testing Next/React) for just $7: https://netninja.dev/p/testing-bundle 🍿👇 Get early access to the course on NetNinja.dev: https://netninja.dev/p/unit-testing-with-vitest-crash-course 🔥👇 Get access to premium courses with Net Ninja Pro: https://netninja.dev/p/net-ninja-pro/#prosignup 🔗👇 Course files on GitHub: https://github.com/iamshaunjp/vitest-unit-testing-tutorial 🔗👇 Vitest Docs: https://vitest.dev/guide/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This video teaches how to use Vitest to write unit tests for a function, including creating test suites and test cases, using assertions, and testing different scenarios. By the end of this tutorial, you will be able to write effective unit tests for your code using Vitest.

Key Takeaways
  1. Create a new file to define the function to be tested
  2. Create a new folder to store test files
  3. Create a new test file to store the test code
  4. Use the describe function to create a test suite
  5. Use the it function to create individual test cases
  6. Import the function to be tested from the examples file
  7. Write test cases for different scenarios
  8. Use assertions to verify expected results
💡 Vitest provides a simple and efficient way to write unit tests for code, with features such as test suites, test cases, and assertions.

Related Reads

Up next
The Difference Between Review Capacity and Review Control | ARDEM Incorporated
ARDEM Incorporated
Watch →