Unit Testing in Javascript

An introduction to unit testing

Photo by Karl Pawlowicz on Unsplash

Unit testing is the process of isolating and testing a small, specific piece, or unit, of code, to ensure each piece is running as expected. In object-oriented programming, an entire class is considered a unit, while functional programming considers an individual method or function. Unit tests are generally differentiated from integration tests, which verify that the units are working properly as a whole.

As a fundamental part of the Test-Driven Development (TDD) methodology, unit tests are written before the actual code is written (the “test-first” approach). These tests drive the creation and design of the code and program, making it an integral and iterative element within the larger development process. TDD allows the developer to avoid being concerned with getting all the logic correct at first. At a high-level, the order of TDD flows as follows:

1. Write a unit test (designating an aspect of the program)

2. Run the test, which will fail because the code does not yet exist

3. Write ‘just-enough’ code so that the test passes

4. Re-factor the code

5. Repeat and accrue multiple tests

In TDD, unit tests are automated with the use of a Unit Testing Framework, which helps the developer create, carry out, and manage test scenarios. This process must be automated and executed often as the program becomes larger and small changes are made to the codebase.

For Javascript applications, there are several unit testing frameworks available. Some of the most popular framework options in recent years have been:

There are several more frameworks out there available for Javascript, including Cypress, Storybook, etc., and all differ based on each app — this article goes into more depth on which is best depending on your project needs.

For early developers, understanding the rationale for implementing unit tests is critical as these tests will decrease the overall time spent on debugging. These tests make the testing phase easier, as they will help identify bugs earlier in the process and any new logic written will not break the previously tested code. Testing frameworks will make the debugging process much less costly in the long run, and as many agree, make building programs much more enjoyable.

--

--

full-stack developer exploring how software can solve real-world problems | https://sarabastian.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store