Here you will learn about Node.js and Node Package Manager (npm). And you will explore how to install npm packages and how to work with package.json. Furthermore, you will learn about testing in JavaScript and you’ll code a simple unit test in Jest. After completing this module, you will be able to:
Learning Objectives
- Describe Node.js and npm
- Explain how to install npm packages
- Describe how to work with package.json
- Explain the process of testing in JavaScript
- List the three most prevalent kinds of testing
- Demonstrate how to code a simple unit test in Jest
- Testing
- Video: Other JavaScript environments – node & NPM
- Reading: Installing Node and NPM
- Video: What is testing?
- Video: Types of testing
- Video: Introduction to Jest
- Video: Writing tests with Jest
- Programming Assignment: Writing a Unit Test
- Video: TDD (Test-Driven Development)
- Practice Quiz: Knowledge check: Introduction to testing
- Module quiz: Testing
- Video: Module summary: Testing
- Reading: Additional resources
Testing
Video: Other JavaScript environments – node & NPM
Summary of “JavaScript’s Journey to the Back-End: Node.js and npm”:
Key Takeaways:
- From Browser to Server: JavaScript, initially confined to the browser, gained server-side capabilities with Node.js, created by Ryan Dahl in 2009.
- Full-Stack Flexibility: Node.js allows writing JavaScript for both client and server, enabling full-stack web development.
- npm Package Manager: Node.js comes with npm, a vast repository of open-source libraries and frameworks installable as modules.
- Command-Line Control: Users interact with Node.js and npm through commands like
node
andnpm
in the terminal. - Project Management:
npm init
creates apackage.json
file that lists project dependencies and facilitates sharing projects. - Benefits:
- Unified language for front-end and back-end development.
- Large ecosystem of readily available modules.
- Simplified project sharing and setup.
Overall:
This video highlights how Node.js and npm transformed JavaScript into a full-stack language and provide developers with a powerful and flexible toolkit for building web applications.
Welcome to JavaScript’s Back-End Adventure!
Ready to embark on a journey where JavaScript breaks free from browser boundaries and conquers the server-side with Node.js and npm? Buckle up, explorers!
Here’s your expedition guide:
Unleashing the Server-Side Potential:
- Origin Story: Discover how Node.js, crafted by Ryan Dahl in 2009, revolutionized JavaScript by enabling it to run beyond browsers, opening doors to server-side development.
- Full-Stack JavaScript: Embrace the newfound power to write JavaScript code for both front-end (client-side) and back-end (server-side) logic, crafting seamless web experiences from top to bottom.
Mastering the Package Manager:
- npm: Your Treasure Trove: Unlock access to a vast repository of over 11 million open-source modules (reusable code blocks) with npm, Node.js’s trusty package manager. Install libraries and frameworks like React, Webpack, Bootstrap, and more with ease!
Commanding the Terminal:
- Speaking Node’s Language: Learn essential commands to interact with Node.js and npm in your terminal:
node
: Execute JavaScript files or code directly.npm install <package-name>
: Install desired modules from the npm repository.npm init
: Create apackage.json
file, the heart of your project’s organization.
Managing Projects Like a Pro:
- Project Blueprint: Understand how the
package.json
file meticulously tracks installed modules (dependencies), ensuring project portability and effortless setup for collaborators. - Sharing the Wealth: Effortlessly share projects with others who can replicate your exact environment by simply running
npm install
—the magic of package management!
Hands-On Practice:
- Set Sail: Install Node.js and npm on your machine (if not already present).
- Chart a Course: Create a new project directory and initialize it with
npm init
. - Explore the Seas: Install modules like
lowercase
to experiment with code transformations. - Navigate with Confidence: Practice using
node
to execute JavaScript files and explore npm’s vast library of modules.
Embrace the Full-Stack Adventure:
- Unified Language: Enjoy the benefits of using JavaScript across both front-end and back-end development, streamlining your workflow and reducing context switching.
- Rich Ecosystem: Tap into the immense collection of ready-to-use modules, accelerating your development process and unlocking countless possibilities.
- Simplified Project Management: Experience the ease of sharing and setting up projects with the well-organized
package.json
system.
Remember, this is just the beginning of your Node.js and npm expedition! Continuous exploration and practice will lead you to discover even greater treasures and create remarkable web applications. Happy coding, adventurers!
Which of the following statements are true for Node.js?
- Node.js is a separate, standalone environment without ties to the JavaScript in the browser.
- Node.js can run in multiple settings, for example, on the command line, in a desktop application, or on the back-end of a web app (on a server).
Well done. Node.js can run in multiple settings, for example, on the command line, in a desktop application, or on the back-end of a web app (on a server). And it’s a completely separate, standalone environment without ties to the JavaScript in the browser.
In 1886, the first internal
combustion engine-powered car was invented by Karl Benz. Soon, there were many cars that used the combustion engine, airplanes, motorbikes, and
boats followed shortly after. People’s ingenuity led to using the combustion engine in places that the inventor
might not have imagined. The same happened to JavaScript. New JavaScript
environments such as Node and npm are now available. JavaScript’s home
is in the browser. That’s the environment
in which it was used for several years. Essentially, it was a
front end only language. Then in 2009, a
developer named Ryan Dao decided to use Google’s
JavaScript V8 engine and make it work on the server. It’s not always easy
being an innovator. Many doubted whether
it was even possible. However, the idea caught on and more people
started getting on board. This is how Node.js
was born and how JavaScript became a language for both front-end and back-end. Node.js is a separate
standalone environment. This means that Node.js can
run in multiple settings. For example, on
the command line, in a desktop application, or on the back end of a web app. Before the introduction
of Node.js, developers had to
build backends in other technologies and
languages such as PHP, Python, C-sharp, Ruby, and Java. After Node.js became available, it was possible to
use JavaScript on the backend or on
the server-side. This means that today you can write full-stack
JavaScript programs. In other words, you can write JavaScript on the client
and on the server. Node.js comes with a
package manager called npm, which stands for Node
Package Manager. The package manager allows
you to use a large number of libraries and frameworks
as Node.js modules. An npm module is a
standalone piece of code that has been published
on the npm website. Sometimes an npm module is also referred to
as an npm package. Now that you’ve
learned about Node.js, you may be wondering how
you can use it locally. Node.js and npm are either
pre-installed on your machine, or you need to install them. Once installed, you
can interact with Node.js and npm from
the command line. For example, you can run the node command inside your
computer’s command line. This is also called a
shell, or a terminal. In the same way, you can
run the npm command. You may be wondering why you
need to run those commands. Well, this is because you use the node command to
run a JavaScript file, or to directly execute
JavaScript code. You use the npm
command to install any node module from
the npm repository. For example, you could install the module named lowercase. Once installed, you can
import this module and use its functions to transform strings to lowercase
in your code. When you want to start
a new project, first, open a folder on your machine where you want
to place your project files, then run the npm command. These projects can be
different shapes and sizes, but they all have at least
one thing in common, the package.json file that gets created after you
run the npm command. The package.json file holds
all the instructions on all the node modules
that are pulled from the npm repository of
open source modules. There are about 11 million
modules in the npm repository. It means that you can get
thousands of hours worth of other developers’
coding by running the npm install command and
adding the package name. Examples of libraries you
can install include React, Webpack, Bootstrap,
and Angular Core. The package.json file updates when you install a new package. It keeps track of
everything you need to have installed
in your project. This makes such projects
easily portable. For example, if you have built a project with a specific number of different node packages, they’re all listed inside
the package.json file. All you need to do is
share this file with, for example, your co-workers. They can have the exact same
setup on their machines simply by running the
command npm install. This install command
reads the contents of the package.json and installs
all the necessary packages, also referred to
as dependencies. Sometimes dependencies also come with their own dependencies. It often happens
that when you run the npm install command, several 100 megabytes
worth of node packages get installed into your project under the node modules folder. In this video, you learned
about the origins of Node.js. You should also be able to
describe what Node.js and npm are and how to use the basic Node and npm
commands on the command line.
Reading: Installing Node and NPM
Reading
Before installing Node.js and npm on your machine, you first need to verify if it’s already installed.
Verifying the existing installation on Windows
On Windows, you can use the WINKEY+r shortcut key, which opens the Run window. Inside the Open: input of the Run window, type cmd and press the enter key. This will open the command prompt.
Inside the command prompt, type:
- node –version
If there is Node.js installed on your Windows OS, it will return a value similar to this:
- v16.14.2
Then you can confirm that you have npm as well, running this:
- npm –version
If npm is installed, you’ll get output similar to this:
- 8.5.0
Verifying the existing Node.js and npm installation on Ubuntu (Linux)
You can quickly open a new bash (terminal) window on Ubuntu by pressing the CTRL+ALT+t shortcut key.
In the bash window that opens, type:
- node –version && npm –version
Both version numbers should appear in the bash window.
Installing Node.js and npm
On Windows OS
In case Node.js and npm are not installed on your Windows OS, navigate to https://nodejs.org.
Locate the big download button, listing the LTS version. As of May 2022, the LTS version available for download is 16.15.0.
On Mac OS – XCode
To install brew, you need to install Xcode first. Homebrew does not come with its own compiler and it needs Xcode installed for it to work correctly. To install Xcode do the following:
- Open a terminal.
- Run the following: shell xcode-select –install
- A popup will appear asking you to confirm the installation. Click on the Install button.
- Agree to the license agreement.
brew
Macs do not come with package managers like most Linux distributions. To make up for this an external tool called brew was created. To install brew, go to the official website ( https://brew.sh/ ) and copy the command provided, open a terminal and run the command :
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Once Brew is insatalled you can run the following command in the terminal
brew install node
Homebrew will download and install the dependancies, once this is complete, confirm the installation by typing
node -v
This will display the Node.js version
Type :
npm -v
to display the NPM version number.
On Ubuntu
Use the CTRL+ALT+t shortcut key to open a new bash window, then run the following commands:
- sudo apt update
- sudo apt install nodejs
That’s it, you should be all set.
For a more advanced set up and troubleshooting, please refer to the additional reading.
Video: What is testing?
Summary of “JavaScript Code Testing”:
Key Takeaways:
- Importance of Testing: Web developers test their code to ensure it functions correctly before launch.
- Testing Methods:
- Manual Testing: Reviewing code and running functions manually to check behavior.
- Automated Testing: Using frameworks like JEST to write tests that define expectations and verify them automatically.
- Benefits of Automated Testing:
- Conciseness: Clear and defined expectations compared to comments.
- Clarity: Explicit arguments and results.
- Repeatability: Easy to run tests repeatedly for consistent checks.
- Red-Green-Refactor Cycle:
- Write a failing test (red).
- Write code to make the test pass (green).
- Refactor code while maintaining passing tests (refactor).
- Test-Driven Development (TDD):
- Focuses on writing failing tests first, then code to make them pass, leading to well-tested code.
- Advantages of Testing:
- Verify code behavior meets expectations.
- Run tests repeatedly with ease.
- Automate testing for efficiency.
Overall:
This video emphasizes the importance of testing JavaScript code and describes various methods and their benefits, particularly automated testing and TDD. It encourages developers to adopt testing practices for reliable and efficient code development.
Welcome to JavaScript Code Testing 101!
Ready to build rock-solid JavaScript applications with confidence? Let’s dive into the world of testing!
Here’s your roadmap to code-testing mastery:
Why Test Your Code?
- Catch Bugs Early: Uncover errors before users do, saving time and reputation.
- Ensure Quality: Guarantee your code works as intended, delivering a smooth user experience.
- Enable Change with Confidence: Make updates fearlessly, knowing tests will catch unintended side effects.
- Facilitate Collaboration: Share code with peace of mind, knowing tests ensure quality and consistency.
Methods of Testing:
- Manual Testing:
- Review code manually and execute functions to check behavior.
- Useful for initial exploration and understanding, but less efficient for repetitive checks.
- Automated Testing:
- Write code that tests your code!
- Use frameworks like JEST to create tests that automatically verify expectations.
- Faster, more reliable, and easily repeatable.
Red-Green-Refactor Cycle:
- Write a Failing Test (Red): Create a test that fails, specifying a desired behavior your code doesn’t yet fulfill.
- Write Code to Make the Test Pass (Green): Implement the necessary functionality to satisfy the test’s expectations.
- Refactor (Improve) Code: Enhance code readability, maintainability, or efficiency without altering its behavior (tests should remain green).
Test-Driven Development (TDD):
- Embrace a mindset of “tests first, code later.”
- Write failing tests before writing the actual code.
- Guides development towards well-tested, modular, and focused code.
Getting Started with Automated Testing:
- Choose a Testing Framework: JEST is a popular choice, but explore others like Mocha or Jasmine.
- Install the Framework: Use npm or yarn to add it to your project.
- Write Your First Test: Start simple, testing a single function or small piece of code.
- Run Your Tests: Use the framework’s commands to execute tests and view results.
Key Concepts:
- Unit Testing: Test individual units of code (functions, modules) in isolation.
- Assertions: Statements within tests that verify expectations (e.g.,
expect(result).toBe(expectedValue)
). - Test Suites: Collections of related tests.
- Test Runners: Tools that execute tests and report results.
Remember:
- Write clear, concise, and focused tests.
- Cover a wide range of scenarios and edge cases.
- Run tests frequently during development.
- Integrate testing into your development workflow.
Happy testing, and create JavaScript applications with confidence!
Which of the following is a correct example of a Jest test?
expect(concatStrings(“123”, “456”)).toBe(“123456”);
Yes, the above code is an example of a JavaScript testing framework syntax.
When you’re building something, you want to make sure it works, and you make sure that
something works by testing it. It’s the same with
JavaScript code. You need to make sure that your JavaScript code works
before you launch it. In this video, I’ll show you how web developers test
their JavaScript code. By the end of this video, you’ll be able to: identify the various reasons why a developer would want
to test their code, explain how the red
green refactor cycle relates to testing, differentiate between manual
and automated testing, and demonstrate an
understanding of unit testing. How do web developers
test their code? Let’s find out by coding a
custom concatStrings function. For example, I can create a concatStrings function to join any two strings
that I give it. In this case, I want the
function to join string A and string B that are
received as arguments, and return the result. For example, I could write
concatStrings a, b, c, and then d, e, f, and the returned result
would be abcdef. When the function
receives number 1 and 2, it returns a three as
a number instead of a string of one and two
together i.e, 1, 2. I can also signal what I want my function to do by
adding comments to it. Adding comments will help
my team understand and remember the expected behavior that I had for the function. A more detailed description would be a good way to make it more obvious as to what my intention is
for each argument. In the comments, I
can even specify the expected behavior when specific values are
given to the function. Adding comments is a step
in the right direction, but it has downsides. It allows me to write
anything I like, so there are no
limits on ambiguity. Also, the common doesn’t need to follow any set structure. There are many custom
testing frameworks available in JavaScript. One of the strengths of such
frameworks is that I don’t have to use comments to
describe my expectations. The test syntax itself becomes
expectation documenting. When I write tests, those tests are a better
alternative to comments in my source code because
they specify what expectations my source
code is trying to satisfy. Tests are also callable, meaning I can execute tests to check if
expectations are met. As I demonstrated earlier, I could execute the
concatStrings function with the first argument
being the string abc, and the second argument,
the string def. I would then expect
the function to return abcdef, when I call it. To write this as an expectation in some testing
frameworks such as JEST, I can use the function
that has the name expect. I then pass the call to the concatStrings function
with the specific arguments. Then I add that to the function, which is another
testing function, and I pass it the
value of what I’m expecting this code to produce. I’m essentially
stating that I expect the calling concatStrings
with abc and def, will return the value abcdef. Testing in JavaScript
lets me verify that the function is behaving
in the way I intended. Testing code in this way
ensures three things. Conciseness as it’s
straightforward and to the point, since there are only
two function calls to explain what is the
expected result. Clarity, because you know exactly what arguments
you’re providing, and repeatability,
as you can run it again and again with the
same arguments each time. Now, I could run multiple function calls
using this syntax. For example, I could have
expected concatStrings 123 and 456 as arguments, and then the function to be
with the argument 123456, and in each instance, the expectations
will be correct, and the code will
behave as expected. In testing
terminology, you would say that your tests are passing. But I’m only halfway
there because it’s still possible from my code
to fail an expectation. For example, if I run the
expect method and pass it an invocation of the
concatStrings function with numbers 1 and
2 as arguments, my expectation of 12 being
the results will fail. This is because when I use the plus operator with two
values of the number type, it performs the mathematical
operation of addition, instead of joining
the two numbers together to form the number 12, like it would form abcdef. If I gave it the
arguments of abc and def. When tests fail, you
say that they are red, and when they pass, you
say that they are green. If a test fails, then it’s a sign that I
need to write the code in such a way that
it passes its test. Once my test passes, I need to improve both the
app’s code and the test code, but without changing
the behavior of either. This is known as refactoring. Refactoring is the
process in which I write my feature code
so that it runs more efficiently or that it’s
easier to read and thus easier to understand for other
programmers on the team. This is done without affecting the results that
the code produces. The only obvious change should
be perhaps the test itself taking less time to run because I’ve optimized
my source code. You want to always
write your code in a way that meets
all expectations. It’s most likely that
some of your tests will be red and some
of them will be green. Red tests are a guide
as to how you need to improve your code to cater
for unmet expectations. As you continue to refine your code in response
to red tests, it becomes a cyclical activity. This is often described as
the red-green-refactor cycle. This cycle is the basis of the test-driven development or TDD approach to programming. Let me explain the TDD approach. First, you write a failing test, then you write your
source code so that the previously
failing test now passes. Finally, you optimize your source code without
changing its results. There are many
advantages of having code that tests other code. For example, you can run it
as many times as you want. You can run the testing
code automatically. The tests can be
repeated without significant cost
in time or effort. To sum up, testing
is how you verify the expectations you have regarding the behavior
of your code.
Video: Types of testing
Software Testing 101: A Developer’s Guide
What is it?
Testing ensures software behaves as expected, fulfilling its intended purpose and meeting user needs. It’s about verifying requirements are met and confirming bug-free functionality.
Different Testing Types:
- End-to-End (E2E): Mimics user interaction with the entire finished product (e.g., testing a website by clicking buttons and navigating pages). Slowest and most expensive type.
- Integration: Tests how different parts of a system interact with each other, ensuring smooth communication and collaboration. Faster and cheaper than E2E tests.
- Unit: Tests the smallest code units (functions) in isolation, independent of other parts. Fastest and cheapest type of testing.
Testing Pyramid:
Visualizes the frequency of each test type, with Unit tests forming the base (most frequent), Integration tests in the middle, and E2E tests at the top (least frequent).
Remember:
- Choose the right type of test based on your needs and project stage.
- Combine different testing types for comprehensive coverage.
- Prioritize efficiency by focusing on fast, cost-effective Unit tests.
Software Testing 101: A Developer’s Guide
Welcome to the world of software testing, where the mantra is “find the bugs before the users do!” As a developer, you know all too well the importance of building robust and reliable software. But how do you ensure your creation functions flawlessly? That’s where testing comes in, your trusty sidekick in the quest for software excellence.
First things first, what is software testing?
Imagine putting your code through a rigorous obstacle course, challenging it with a variety of scenarios and user interactions. That’s essentially what software testing is! It’s the systematic process of verifying that your software meets its requirements, works as intended, and is free from errors.
Why is it important?
Think of it like building a bridge. You wouldn’t trust a bridge without rigorous testing, right? Similarly, untested software can crumble under real-world usage, leading to bugs, crashes, and frustrated users. Testing identifies these flaws early on, saving you time, money, and reputation.
Now, let’s explore the three main testing types:
- Unit Testing: The microscopic detective! Unit tests focus on the smallest building blocks of your code, like individual functions or methods. They’re quick, efficient, and crucial for ensuring the fundamental logic of your program is sound.
- Integration Testing: The team player! Integration tests assess how different parts of your software interact with each other. Do the gears mesh smoothly? Do components communicate effectively? This type of testing ensures your code doesn’t crumble when working together.
- End-to-End Testing: The user experience champion! E2E tests simulate real user interactions with your entire software product. It’s like asking a friend to click through the app and report any hiccups. This type of testing verifies the whole user journey is smooth and intuitive.
Remember, these testing types are like your tools in a toolbox. Choose the right one for the job! Unit tests are your trusty screwdrivers, quick and precise for isolated components. Integration tests are your wrenches, ensuring smooth collaboration between parts. E2E tests are your hammers, making sure the full-fledged system stands strong.
Beyond the types, keep these tips in mind:
- Start early and test often: Don’t wait till the end to catch bugs. Integrate testing throughout your development process.
- Automate where possible: Repetitive tasks like running unit tests can be automated, freeing up your time for more creative endeavors.
- Think like a user: Put yourself in the user’s shoes and design test cases that reflect real-world scenarios.
- Document everything: Keep track of your tests, bugs found, and fixes implemented. This creates a valuable trail for future reference.
Software testing is not just a chore, it’s an art! By honing your testing skills, you become a software architect, building not just code, but a reliable and delightful experience for your users. So, grab your testing toolkit, embrace the challenge, and dive into the world of software quality!
Remember, this is just a starting point. The world of software testing is vast and full of exciting techniques and tools. Explore further, experiment, and keep your quest for quality code alive!
Which type of testing involves the process of testing the smallest units of your source code in isolation?
Unit testing
Yes, unit testing involves the process of testing the smallest units of your source code in isolation.
as a developer, you are tasked
to test a piece of software, how would you do it in
the next few minutes. I am going to explain
what software testing is. I’m going to introduce you to
the three most used types of testing. You might say that testing a piece of
software at a high level means making sure that it behaves as expected in any
modern software development project. These expectations are recorded
as software requirements. There are many aspects of software
testing, but for now let’s think of it as the act of confirming that it works as
outlined in the software’s requirements. Now that I have a working
definition of testing, let’s think about how you might
approach it for a UX designer. Testing might mean making sure that
the website looks and behaves as expected. For project manager on a software project
testing might mean that a specific piece of software works well with other parts
of your system for a software engineer. Testing might mean writing code
that doesn’t break the existing functionality is bug free and
satisfies the requirements as set out in a given task based on what
your motivations are. There are several ways that you can
test your software projects practically. This means that there
are different kinds of testing. Now, I’ll discuss the following three
types of testing into in testing R. E to a integration testing and
unit testing. Let’s start with into in testing a real
life example of E two EE testing would be if a laptop manufacturer,
let his employees open some off the assembly line laptops turn them on and
use them just like a normal user would do to make sure that the entire
in product behaves as it should. More specific to web development into. In testing tries to imitate how
a user might interact with your app. This means that in Italy testing you
need to open your web application in a browser and then test it by
interacting with the page the same way a user might interact with it. For example, clicking on the log in
button are going through the process of adding an item to the shopping cart. In other words, you’re testing the entire finished software product from
the perspective of the end user. Now here’s something you
may find interesting. The person testing the app
doesn’t have to be a developer. Finally, E two E tests are the slowest and
take the most time to set up and run. Here are a few examples of eat away
testing frameworks available on the market. Web driver Js Protractor and Cyprus. Next I’ll discuss integration testing. Integration testing is testing how parts
of your system interact with other parts of your system. In other words, it’s testing how separate
parts of your apps work together. Let’s explore two examples of integration
testing software react testing, library and
enzyme integration tests are faster and cheaper than E two E tests but
not as fast or as cheap as unit testing. What is unit testing. Let’s have a look. Unit testing is the process of
testing the smallest units of your source code in isolation. A good example of this is functions. A unit is the smallest piece of
code that you can test separately from the rest of the app. Practically the smallest unit of testable
code in Js is usually a function or a method. Unit tests are self contained. They’re meant to test code in isolation, preferably separate from
the rest of your app. This makes unit tests fast to run and
easy to write. So That was a brief overview of
the three different kinds of tests. Together, they are sometimes represented
as a three level testing pyramid. First at the base of the Pyramid
are the unit tests which have the highest speed and the lowest cost. Then in the center of the pyramid are the
integration tests of average speed and expense. And finally at the top of
the pyramid are the E two E tests, the slowest and
most expensive tests to run. You are now familiar with the three
most common ways that you can test your applications
Video: Introduction to Jest
Jest Framework for JavaScript Testing:
- JavaScript lacks built-in testing features.
- Jest is a popular JavaScript testing framework, used for React and beyond.
- Key features:
- Code coverage: Measure code tested by tests (higher % = fewer potential bugs).
- Mocking: Isolate code under test from dependencies (e.g., mock server data for front-end testing).
- Snapshot testing: Verify DOM stability after code changes.
- Benefits:
- Independent front-end testing (mocks avoid back-end dependency delays).
- Easy asynchronous code testing.
- Simple Jest mock functions.
In short, Jest equips you to effectively test your JavaScript code, boosting quality and developer efficiency.
# Jest Framework for JavaScript Testing: A Comprehensive Guide
Welcome to the world of Jest, where testing JavaScript code becomes a breeze! This tutorial will equip you with the knowledge and tools to write effective tests, ensuring the quality and reliability of your JavaScript applications.
Here’s what we’ll cover:
- Introduction to Jest
- Setting Up Jest
- Writing Your First Test
- Key Features
- Code Coverage
- Mocking
- Snapshot Testing
- Advanced Features
- Best Practices
Let’s dive in!
# 1. Introduction to Jest
- Why Jest?
- Created by Facebook, widely used for React testing and beyond.
- Simple setup and configuration.
- Fast, zero-configuration testing platform.
- Built-in mocking and snapshot testing capabilities.
- Clear and concise test results.
# 2. Setting Up Jest
- Installation:
npm install --save-dev jest
- Configuration: Create a
jest.config.js
file (optional) for customization.
# 3. Writing Your First Test
- Test file structure:
filename.test.js
orfilename.spec.js
- Test structure: JavaScript
test('my first test', () => { expect(true).toBe(true); });
- Running tests:
jest
# 4. Key Features
- Code Coverage:
- Measures the percentage of code covered by tests.
- Aim for high coverage to reduce potential bugs.
- Generate coverage reports with
jest --coverage
.
- Mocking:
- Isolates code under test from external dependencies.
- Create mock functions for controlled testing.
- Useful for front-end testing without back-end reliance.
- Snapshot Testing:
- Captures rendered UI output for comparison in future tests.
- Detects unexpected UI changes.
# 5. Advanced Features
- Asynchronous Testing: Simplified handling of async code.
- Watch Mode: Automatically re-runs tests on file changes.
- Custom Matchers: Create custom assertions for specific needs.
# 6. Best Practices
- Test early and often.
- Write clear and concise tests.
- Focus on testing logic, not implementation details.
- Aim for high code coverage.
- Use mocks effectively.
- Take advantage of snapshot testing for UI components.
Congratulations! You’re now equipped to confidently test your JavaScript code with Jest. Happy testing!
Which of the following features does Jest provide? Check all that apply.
Jest can be used to write unit tests.
That’s correct! Jest allows you to easily work with unit tests.
A range of frameworks can be tested with Jest.
That’s correct! Jest lets developers test a range of code types.
Jest supports code coverage.
That’s correct! Jest uses code coverage to measure what percentage of code is covered by tests.
At this stage, you might be
familiar with the concept of testing your code to make sure it’s working
as you intend it. You might also have come across some syntax of
testing frameworks. But what about a language like JavaScript that has no built-in
testing functionality? For JavaScript, you can use
testing frameworks like Jest. Over the next few minutes, I am going to introduce you to the features of the
Jest framework, code coverage, mocking,
and snapshot testing. It is quite a mouthful.
Let’s get started. JavaScript doesn’t have
built-in objects or methods that would allow
for tests to be written. Therefore, many
different libraries have been built to tackle
the issue of testing. Some examples of these
libraries include Jasmine, Mocha, Karma, and qUnit. Then there is the one
that you will cover now, namely the Jest
testing framework. Jest is a JavaScript
testing framework. It’s often used for
testing code like React, a JavaScript library
maintained by Meta and a community of individual
developers and companies. Besides plain JavaScript and React code just allows
you to test Babel, TypeScript, Node, Angular, Vue, and various
other frameworks. Jest also supports
code coverage. Code coverage is a measure of what percentage of my
code is covered by tests. If I say that I have an
80 percent code coverage, that means that
only one-fifth of my entire code base is
not covered by tests. But even 100 percent
code coverage doesn’t mean that you have tested for every conceivable
expectation. It just means that there are some expectations tested
for each line of my code. Still, code coverage
is a handy tool to gauge the amount of my code base that’s
included in tests. The higher the code coverage, the lower the chance of
having unidentified bugs. As a rule, the higher the
percentage of code coverage, the lower the amount of time
required to write new tests. This, however,
depends on whether there are incomplete
software requirements pending or if you are going to receive more requirements
in the future. Next, let’s cover the
concept of mocking. Mocking allows you
to separate the code that you are testing from
it’s related dependencies. In other words, you can
use the mocking features to make sure that your unit
testing is stand-alone. For example, you can test the front end functionality
of your web app by mocking the data as
if it came back from a server when in fact it
came from the client. Mocking is especially
helpful because very often web applications are
built by teams of developers. Some developers work
on the backend of a feature and others
work on the front end. This could result
in bottlenecks. Take an example where the team decides to build a
new feature that lists the address book of users of the app
on the front end. The actual user related data for this feature would
come from the server. But what if a back-end
developer was a bit late in developing
their part of the feature? Then a front end developer
would be stuck waiting for the back-end
developer to complete their work before the
front-end code can be built. With mocking you can
avoid this bottleneck. Mocks, allow you to pretend that the users
are already there. The needed data comes from the mock rather than
from the backend. This allows the
front-end developers to finish their site of the
new feature independently. In certain cases, developers can use mocking to ship
features faster. Some libraries, such as sign-on, focus specifically on mocking. But the great thing about
Jest is that you use it’s mock functions without any
additional installations. In Jest you use mocking by
employing Jest mock functions. It’s also easy to test
asynchronous code in Jest. There are no difficult
setups and tests are relatively easy to code even for newcomers
to the framework. Finally, Jest allows you to
perform snapshot testing. Snapshot testing is used by developers to
verify that there are no regressions in
the DOM of our apps after some changes to
the code base are made. You’re now familiar with
the concept of testing your JavaScript code using the Jest testing
framework. Great work.
Video: Writing tests with Jest
Here’s a summary of the key points from the video:
1. Setting Up Jest:
- Check for Node.js and npm: Use
node --version
andnpm --version
. - Install Jest locally:
npm install --save-dev jest
- Update package.json: Change the “test” script to “jest”.
2. Creating a Test File:
- Name it:
addFive.test.js
(for a file namedaddFive.js
) - Import the function:
const addFive = require('./addFive');
3. Writing a Test:
- Use
test
method:test('returns the number plus five', () => { ... });
- Assertion:
expect(addFive(2)).toBe(7);
4. Running Tests:
- Command:
npm run test
- Output: Pass or fail results
Key Points:
- Use a
package.json
file to manage project dependencies. - Install Jest locally for project-specific testing.
- Use clear and descriptive test names.
- Write assertions to check expected behavior.
- Run tests with
npm run test
.
What will happen when you run this piece of code on the command line at the root of your project's folder: npm install --save-dev jest?
It will add Jest as a devDependency inside package.json.
You are correct! When you run this piece of code on the command line at the root of your project’s folder it will add Jest as a devDependency inside package.json.
In this video, you’ll
explore how to install the packages needed to test your JavaScript code
and the Jest framework, as well as how to set up a test. Let’s say I need to
write a function that takes a value and
adds five to it. I’ll start by
creating a new file and naming it addFive.js. The code in the addFive
function starts with function addFive and then
vowel in parentheses. In between curly braces, I have returned vowel plus
five on the next line, and then on a new line, I have module.exports
equals add five. This is a simple function
which will make it easier to analyze when
I write tests for it. I’ve also added a line to
export this function so that it can be used by other
files in this project. Now I’ll switch over to using the jest testing
framework to write some expectations of how
this function should behave. Before doing so,
I’ll check if I have no JS and NPM installed
on my system. In the terminal tab, I type node dash, dash version to
check for NodeJS. And it shows that I
have version 16.15. Now I check for NPM and it tells me I have version 8.5 installed. One more step before I
continue is to check if Jest installed by typing
Jest dash dash version. In this case, it returns
command jest not found, meaning that it is not globally
installed on my machine. So I’ll install it for this
project using only NPM, since jest needs
NodeJS to run and NPM as a way to install Node modules into
my web projects. I’ll first type and run NPM dash y to add a package.json file. The dash y File
automatically answers yes to all the questions that init command asks during
installation. Now I have my package.json file. In other words, I have
a way to keep track of node modules that
this project depends on. Since I want to use the
jest testing library, I’ll need to install it locally, which means installing
it for this project. So I run NPM install dash, dash, save, dash, dash Jest. After a few moments, the package.json file will be updated with the addition of
the jest testing library. I also have a folder called
Node underscore modules, which is where the code for all the modules in this
project is stored. In the package.json file, I’ll need to make a few
changes to the script section. In the test entry, I replace
the text that is assigned to test with jest within
double-quotes and save it. Now when I run the
command NPM run test, it will run the Jest
command in this folder. What does this Jest command do? It runs tests for the
code in my project. Right now, I only have a
single file, addFive.js. So it makes sense to create a test file for this
one JavaScript file. I’ll name it addFive.test.js. In the naming convention I use, I add the dot test just before the dot js section
of the file’s name. To set this file up, I’ll first import the exported addFive
function by typing const, addFive equals require,
and then in parentheses, backtick dot, forward
slash, addFive, backtick. The reason for the forward-slash
is to indicate that the function is in the same
folder as a test file, and I’ve omitted the dot js because Node understands
what I mean, even if I don’t use it. So my expectation is
that this function returns whatever value
I input plus five. To check, I’ll use
the test method with a string as a parameter
that describes the test. This string will be output
in the command line when I run the test along with
the words pass or fail, and the function to run when I execute the NPM
run test command. The function will check if
my expectation is correct. The string will be output
in the command line when I run the test along with
the words pass or fail, and the function to run when I execute the NPM
run test command. The function will check if
my expectation is correct. I have test and as
the first argument, I have the string returns
the number plus five, which is what I
want to output on the command line when
the test is run. Then as a second argument, I have a function which
checks my expectation, I’ll save and run the test
and I get back a pass result. In this video, you learned
how to ready your system for testing in Jest and how
to set up and run a test.
Programming Assignment: Writing a Unit Test
Reading
Lab Instructions: Unit Testing
Tips: Before you Begin
To view your code and instructions side-by-side, select the following in your VSCode toolbar:
- View -> Editor Layout -> Two Columns
- To view this file in Preview mode, right click on this README.md file and
Open Preview
- Select your code file in the code tree, which will open it up in a new VSCode tab.
- Drag your assessment code files over to the second column.
- Great work! You can now see instructions and code at the same time.
- Questions about using VSCode? Please see our support resources here:
Visual Studio Code on CourseraTo run your JavaScript code
- Select your JavaScript file
- Select the “Run Code” button in the upper right hand toolbar of VSCode.
Ex: It looks like a triangular “Play” button.
Task 1: Add Jest as a devDependency
Open terminal. Make sure that it’s pointing to jest-testing
directory.
Install the jest npm package using the npm install command and the –save-dev flag.
Verify that the installation was completed successfully by opening the package.json file and confirming that the “devDependencies” entry lists jest similar to the following:
"devDependencies": {
"jest": "^28.0.0"
}
Task 2: Update the test entry
In the package.json file, locate the “scripts” entry, and inside of it, update the test entry to jest
.
Task 3: Code the timesTwo function
Open the timesTwo.js file and add a function named timesTwo
. The function should take number as input and return the value 2 multiplied by the number. Export the timesTwo function as a module.
Task 4: Write the first test
Code a test call with the following arguments:
- The description that reads: “returns the number times 2”.
- The second argument should expect the call to the timesTwo function, when passed the number 10, to be 20.
Task 5: Run the first test
With the terminal pointed at the jest-testing
directory, run the test script using npm.
package.json
{
"name": "jest-testing",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest"
},
"author": "",
"license": "ISC",
"devDependencies": {
"jest": "^28.1.3"
}
}
timesTwo.js
// Task 1: Code the timesTwo function declaration
function timesTwo(val) {
return val * 2
}
// Task 2: Export the timesTwo function as a module
module.exports = timesTwo;
timesTwo.test.js
const timesTwo = require('./timesTwo');
// Write the first test
test('returns ...', () => {
expect(timesTwo(10)).toBe(20)
});
Video: TDD (Test-Driven Development)
Summary of Test Driven Development (TDD):
What is it?
TDD is a software development process where you write tests before writing the actual code. This ensures that your code meets the requirements and works as expected.
Steps:
- Read requirement: Understand what the new feature should do.
- Write failing test: Create a test that fails because the feature isn’t implemented yet.
- Write minimal code: Implement just enough code to make the test pass.
- Run test: Ensure the test passes with the new code.
- Refactor code: Improve the code without changing functionality.
- Repeat: Red-Green-Refactor loop for each requirement.
Benefits:
- Minimizes regressions: Catches bugs early before they affect users.
- Strong test coverage: Ensures all requirements are met.
- Easy automation: Tests can be run automatically to maintain quality.
- Improved documentation: Tests serve as clear specifications for code.
Key terms:
- R – Red: Failing test representing missing functionality.
- G – Green: Passing test after implementing the feature.
- Refactor: Clean up the code without changing behavior.
By following the TDD cycle, you can write high-quality code that meets requirements and is less prone to bugs.
Demystifying Test Driven Development (TDD): A Beginner’s Guide
Ever written code, launched it with excitement, only to encounter frustrating bugs? Test Driven Development (TDD) can be your knight in shining armor!
What is TDD?
Imagine building a house, but instead of hammering nails first, you meticulously map out blueprints, ensuring every beam and brick fits right. That’s TDD in a nutshell! It’s a software development approach where you write tests before writing code.
Why TDD?
Benefits galore! Let’s name a few:
- Bug Squasher: Identifies bugs early, saving you time and frustration later. ♀️
- Confidence Booster: Ensures your code truly meets requirements, leading to happier users and stakeholders.
- Documentation Delight: Your tests become living documentation, clarifying code functionality for you and your team.
- Refactoring Rockstar: Encourages clean, modular code that’s easy to maintain and adapt.
The TDD Dance:
TDD flows like a graceful waltz:
- Red Step: Understand a new requirement. Write a test that fails because the feature doesn’t exist yet.
- Green Step: Write minimal code just enough to make the test pass. Think of it as building the foundation.
- Refactor Step: Polish your code, improve readability, and ensure it’s well-structured without changing functionality. ✨
Repeat this Red-Green-Refactor cycle for each requirement, and voila! You’ve built a robust, well-tested system.
Getting Started:
- Pick your tools: Choose a testing framework like Jest for JavaScript or JUnit for Java. ️
- Start small: Don’t tackle a whole project at once. Begin with simple features and gradually level up.
- Embrace the red: Don’t fear failing tests. They’re your guideposts to success!
- Practice makes perfect: The more you TDD, the more comfortable and confident you’ll become.
Remember: TDD is a journey, not a destination. Embrace the learning curve, and you’ll soon be writing code with newfound confidence and precision. So, step into the world of TDD, and watch your coding skills blossom! 🪄
Bonus Tip: Check out online resources and tutorials for specific programming languages and frameworks. The TDD community is vast and eager to help!
Happy coding!
Following the TDD approach has many benefits. Select all the benefits following the TDD approach has for you as a developer. Check all that apply.
Minimize regressions. Implementations can be tested using various inputs.
That is correct! The benefits the TDD approach has for you, as a developer, is Minimizing regression and the fact that your implementations can be tested using various inputs.
Every piece of software is built according
to formal or informal requirements. The purpose of the requirements
is to explain, in human language the intricacies
of what the piece of software does. So how did the requirements tie in with
the practice of test driven development? Let me explain test driven development. R T D D for short is a streamlined
process of writing code that will satisfy some requirements. Let’s unpack this process
a bit on a high level. A software development teams work consists
of the following receiving requirements which will become a feature of
the app that’s being developed. Writing a failing test for that to
build feature before it gets built. Making this failing test pass by coding
that given feature in comparison with the traditional development process, that TDD approach might
seem somewhat upside down. I am now going to demonstrate the TDD
approach by writing a failing test for a javascript file and then writing code to make this test
pass to understand how TDD works. Consider the following
real life situation. Suppose you have to perform a task,
drive your car to work. You leave your house and
walk up to your car, only to find out that you don’t
have your car keys with you. Then you remember you left your
car keys in the cabinet and you simply forgot to take
them what you did there. In this imagined scenario
is the opposite of TDD. You first walk to your car and only
then did you check if you had your car keys if you did these things
using the TDD approach, you would do the following first. You check or
test if you have your keys with you. Your test fails because
you don’t have them. They’re in the cabinet. Then you perform the action of
getting your keys from the cabinet. Finally, you check or test if you have
your keys this time you have them. So your test now passes. What is described here
is the essence of TDD. Let’s go through these
steps again this time, pretend that you’re
implementing TDD in your code. Imagine that you need to write
code in a test driven way. Since your coding the TDD way
you first write the test, even before you’ve written any
actual implementation, for example, you test if a function
named status of keys exists, you then use some testing functions
from a testing framework. Since you haven’t written your
source code implementation. The test fails. Next you run your test. The test fails because
there’s no status of keys. Function declared. The logic of your test code is
expect that the function status of keys exists in your source code. You declare a function
named status of keys. You run the test. Again, it checks if there is such
a function and it confirms it exists. So the test passes, it’s important
to note that one of the rules of TDD is that you should write as little
code as possible to make the test pass for this test to pass, it’s enough to just
declare a function with the name next you receive another requirement which is
as follows except a keys variable, which should be set to true and
console log the keys variable. So the requirement states the status
of keys function should accept a previously declared keys variable,
which should be set to true. The status of keys should then console
log the value of the keys variable. So you write another test which fails
again since you have yet to write the implementation, you write it and
your previously failing test now passes. Finally, you examine
your function code and realize that the indentation is all wrong. There are also too many
unnecessary comments. So you clean up your code and run the test again to confirm that you
haven’t accidentally made any errors. The test still passes,
so everything is okay. That is the TDD approach in a nutshell,
let’s go over it one more time. In a scenario as a member
of the development team, your task is to read the requirements for
the software that you are writing. The requirements are passed to
you by the project manager. So you get your first task for
the day and start coding the TDD way. First you read the new requirement. Next you write a failing test,
then you update your source code. So it resolves the requirement After
that you run a test that passes Finally, you re factor your implementation. This process is usually
explained in three words. Red, Green. Re factor,
red represents the failing test. Green on the other hand, represents the passing test after
you make updates to the source code. The re factor represents the final
tweaks to the code that don’t change implementation details,
which can always be confirmed by running another subsequent
test when implemented correctly. TDD brings huge benefits to
an organization because it allows for automated testing in any platform projects
grow bigger over time and become complex. Making sure that all the tests are passing
is a strong signal that the current requirement and
all the previous requirements for this piece of your app have been delivered
successfully and that nothing is breaking. Test driven development
has many advantages. Here are a few with TDD, you are
minimizing regressions that is accidental bugs introduced to old code by coding
a new requirement and you also have proof that your new implementation is
not breaking other parts of the app. You can automate these tests easily and
thus keep verifying again and again that the system works as expected. You can test your implementations with
various inputs and the tests become a specific kind of documentation for
the new members of your team. In this video, you learned how test
driven development, r t d d works, You also covered the steps
involved in the TDD approach and that it is implemented in
Red Green re factor cycles
Practice Quiz: Knowledge check: Introduction to testing
What is the correct way to export the timesTwo function as a module so that Jest can use it in testing files?
module.exports = timesTwo
That’s correct! This is the correct way to export the function.
Testing is a way to verify the expectations you have regarding the behavior of your code.
true
That’s correct! Testing is good practice as a software engineer for verifying expectations.
Node.js can be used to build multiple types of applications. Select all that apply.
Command line applications. Desktop applications. Web application backends
When the following test executes, what will the test result be?
function add(a, b) {
return a + b;
}
expect(add(10, 5)).toBe(16);
Fail.
That’s correct! The expectation will fail as the function will return 15 which does not equal 16.
Which of the following is the slowest and most expensive form of testing?
End-to-end testing (e2e)
That’s correct! End-to-end testing (e2e) is the most expensive as these tests take the most time to set up and run.
Mocking allows you to separate the code that you are testing from its related dependencies.
true
That’s correct! Mocking allows you to isolate the code being tested in your unit tests.
Module quiz: Testing
The idea of having separate, small pieces of code that are easy to test is called what?
Unit testing
That’s correct! Unit testing is focused on testing small, specific “units” of code.
When the following test executes, what will the test result be?
function multiply(a, b) { return a; } expect(multiply(2, 2)).toBe(4);
Fail.
That’s correct! The function will fail because it has a bug which returns only the a variable. Therefore, 2 is returned from the function which does not match the expectation.
Node.js is typically used to do which of the following?
Build web application backends
That’s correct! Node.js is a popular JavaScript runtime for building backends.
Which of the following are NOT one of the three types of testing?
Post-hoc testing
That’s correct! Unit testing, integration testing, and end-to-end testing are the three types of testing.
True or False: You can install packages from the npm repository using the node command.
False
That’s correct! The npm command is used to install packages.
package.json is used to do which of the following?
Store all the dependencies required for application.
That’s correct! package.json contains human-readable metadata about the project (like the project name and description) as well as functional metadata like the package version number and a list of dependencies required by the application.
Which of the following statements are NOT benefits of using Test-Driven Development or TDD?
You can run tests without setting them up.
That’s correct! Test driven development minimizes regressions, provides proof that you’re meeting your expectations, and allows for easy automation for continuous testing.
What is the recommended way to separate the code that you are testing from its related dependencies?
Mocking
That’s correct! Mocking allows developers to simulate the behavior of dependent code during tests.
Video: Module summary: Testing
Summary of Software Development Testing Module:
Key Learning Points:
- JavaScript History & Full-Stack Development:
- Introduction to JavaScript and its evolution.
- Building full-stack applications with JavaScript.
- Node.js & NPM Setup:
- Understanding Node.js and NPM in software development.
- Installing and configuring Node.js and NPM environment.
- Importance of Code Testing:
- Recognizing the need for testing code before deployment.
- Benefits of proper code testing.
- JavaScript Testing Methods:
- Introduction to manual and automated testing.
- Differentiating between unit, integration, and end-to-end testing.
- Jest Framework:
- Exploring features and capabilities of Jest for JavaScript testing.
- Mocking & Snapshot Testing:
- Grasping the concepts of mocking and snapshot testing in Jest.
- Testing JavaScript Files with Jest:
- Understanding how to test JavaScript files using Jest framework.
- Writing Unit Tests:
- Demonstrating the ability to write basic unit tests for JavaScript code.
Overall takeaway: This module provided a comprehensive introduction to code testing for web developers, specifically focusing on JavaScript and the Jest framework. You’ve gained valuable skills and knowledge essential for building high-quality software.
Next Steps: Keep up the learning momentum and join the next module to further expand your software development skills!
You’ve completed the testing and
compatibility module. Well done. in this module,
you got an introduction to code testing. This was an insight into how web
developers test their JavaScript code. Join this module,
you explored the importance of testing and you examined Javaccript testing methods. Let’s finish up now with the recap of
the material included in this module and summarize the content by focusing
on the key learning points. The history of the development of
the JavaScript language was outlined and you learned that today it is possible to
write full stack programs with JavaScript. You should now know how to
describe what no J S and N PNR and install and
set up node JsSand NPM. In any development environment you
need to check that your code works properly before you move to the next
phase of its development or release a completed program to users. An example of using the contact strings
function to join two strings served to demonstrate how commenting can help to
indicate your codes intended behavior and how testing in JavaScript verifies that
a function is behaving in the way that it was intended. Having completed that section of the
module, you should now be able to identify reasons why a developer would
want to test their code,. Differentiate between manual and
automated testing, identify and describe the three different
kinds of testing and explore the features available to web
developers within the jest framework. Additionally, you should be able to
understand the concepts of mocking and snapshot testing, explain how to
test JavaScript files with jest and demonstrate how to write a unit test. You’ve put a tremendous effort
into getting this far and gained some critical skills by learning
about the need for code testing. You’ve also explored various methods
used for JavaScript testing. Great work. You’ve completed another key part of
your software development education, keep the learning momentum going and
be sure to join me for the next module.
Reading: Additional resources
Reading
Here is a list of resources that may be helpful as you continue your learning journey.
MDN: Server-side website programming