Let’s start with what’s wrong with testing.

“Writing tests takes too long. We’re moving too fast for that.”

“It’s extra code to maintain.”

“That’s what QA is for.”

“It doesn’t catch enough errors.”

“It doesn’t catch the important errors.”

“This is just a little script/simple change. It doesn’t need a test.”

“But the code works.”

“The boss/client is paying for features, not tests.”

“No one else on the team cares and will break the test suite and I’ll be trying to be Commissioner Gordon in a Gotham gone mad.”

About That Last Quote...

This one is actually a lot harder. Here, testing isn’t the problem. This dynamic suggests a small and/or inexperienced team with a lack of leadership. Changes to this outlook on testing and quality could evolve over time (slowly, as in one person at a time), or be mandated from above (unlikely without new leadership).

Unfortunately, if you’re in a team full of “cowboys”—coders who just push code, ignoring quality and testing—the most likely outcomes are frustration and unpredictable breakages (and unpredictable hours).

“Leave this toxic team immediately” is not the only solution, as there may be other benefits and constraints in your situation. But projects that have some focus on quality typically offer more stability (less turnover), better compensation, and more learning opportunities.

Of all the possible strawman quotes listed, this one stands out as one where the fix is not simply to “recognize and enjoy the benefits of testing after becoming comfortable with it.” But if the engineering culture actively discourages testing, it is actively discouraging quality. It’s harder to change culture than your own personal outlook and experience with testing. If you’re not in a leadership role, your personal development is best served by avoiding or leaving these projects.

At first glance, “The boss/client is paying for features, not tests” may also look like a cultural problem. However, it’s unlikely that this is actually enforced at a code level. If you’re efficient at writing tests, only the shortest professional engagements would move faster without having a test suite in place. In these cases, it’s best to use your judgment to write quality software. No reasonable boss or client would refuse any verification that the software works correctly. If you can automate the process efficiently, your professional standard of quality should include writing tests. If you can’t do that efficiently due to your lack of skill with testing tools, you can’t help but give in to lower standards until you can gain experience. First, recognize that when you do manual checks, you are testing; you’re just not automating your tests. That should be sufficient motivation.

All this is to say that the solution to your internal resistance to testing is to get more comfortable with testing as you develop your standard of quality. External resistance, if strong enough, is resistance to quality and professional development. This book should help you overcome the internal resistance. The external resistance is all about networking and experience in choosing projects.

If you have these opinions, you’re certainly not alone, and on a given project you might even be right. There are real difficulties with writing tests. One thing to keep in mind, though, is that when things are frustrating, beneficial as they might be, some coders may feel a sense of “cognitive dissonance,” which can escalate a need to gather more evidence as to why testing is useless/costly/not your job. Here, you’re acting like Aesop’s fox who, after grasping for grapes and failing, consoles itself by saying that they must have been sour anyway. If ensuring software quality through testing is hard, then it must not be important, right?

That might be a helpful adaptation for dealing with regrets and disappointments in life that are outside of your control, but without recognizing the benefits of testing, you’re closed off to a completely different way of writing code. The grapes aren’t sour, and unlike the fox, you can find a ladder to reach them.

The main purpose of testing is to have confidence in your code. This confidence cannot be born in a vacuum. It’s forged in the skepticism developed from seeing code that errs and resists change. As we’ll see in “Debugging and Regression Tests” , confidence is the best indicator of what and how to test. The biggest reason to learn testing is to develop your senses of confidence and skepticism when looking at a codebase. If that sounds a bit abstract, don’t worry. More concrete reasons for testing are coming up in the next section.

First, a quick note on some terms we’ll be using:

Coverage (also code coverage or test coverage)

This is a measurement, most usefully a percentage, of the lines of code that are covered by tests.   

High-level and low-level

Just like ordinary code, tests can be broad (high-level) or more involved in details (low-level). These are general terms, but for the two most important types of tests we’ll cover, high-level will generally correspond to “end-to-end tests,” whereas low-level will correspond to “unit tests.”

Complexity

This is a measurement of the pathways through the code. It tends to be more casually and generally referred to as complexity , rather than its ancestor cyclomatic complexity . 

Confidence

This is, ultimately, why we test. Full test coverage gives us confidence that the whole codebase behaves as we intended. There are some caveats to this, covered by “Nonfunctional Testing” and “Test-driven development” .

Exercised

A line of code is said to be exercised if it is run by the test suite. If a line is exercised, then it has coverage.

Technical debt

This is the situation where a lack of confidence and trust (via complexity and a lack of test coverage) in the codebase results in more guesswork and slower development overall.

Feedback loop

This is the gap between writing code and knowing if it is correct. A “tight” or “small” feedback loop (versus a “loose” or “long” one) is good, because you know right away when your code is functioning as expected.

Mocking and stubbing

These are both ways of avoiding directly exercising a function, by replacing it with a dummy version. The difference between the two is that mocking creates an assertion (pass/fail part of a test), whereas stubbing does not.

The Many Whys of Testing

  1. You’re already doing it!

    Well, this is a bit of an assumption, but if you run your code in the console or open up an HTML file in the browser to verify behavior, you are testing already, albeit in a slow and error-prone way. Automated testing is just making that process repeatable. See “Manual Testing” for an example.

  2. Refactoring is impossible without it.

    Refactoring, as discussed in Chapter 1 , is completely impossible without guaranteeing behavior, which, in turn, is impossible without testing. We want to refactor and improve code quality, right?

  3. It makes working with a team easier.

    If your coworker writes some broken code, the test suite should let you both know that there’s a potential problem.

  4. Tests are ideal for demonstrating (not documenting) functionality.

    Making and maintaining documentation is a whole different discussion. But assuming you don’t have documentation in place, tests can demonstrate the behavior you want out of your code. Exclusively relying on tests to document the code (especially for an externally facing interface) is not a great idea, but it’s a step up from having only the source code as a reference.

  5. You’re not just verifying the behavior of your code.

    Not every software library you use will have the same policy on updates and versioning. You could unintentionally upgrade to a bad or conflicting version, and without testing, you wouldn’t realize it had broken your code. Not only that, but when you bring a new library in or use a new part of it, do you want to exclusively rely on the tests the library has in place for itself? What if you modify that library? Can you still trust just its developer’s tests then?

  6. Tests are crucial for big upgrades.

    You really want to start using the latest version of big framework/new runtime. How can you upgrade responsibly and quickly? Just quickly? YOLO. Deploy it. It’s probably okay, right? Right? Probably not. Just responsibly? Manually go through every possible code path and verify that everything does what it is supposed to, constructing necessary data objects as you need them. For both speed and responsibility at the same time, you need a test suite. There is no other way.

  7. You’ll catch bugs early.

    The earlier that bugs are caught in the development cycle, the easier they are to fix. Before you write them is ideal. If the quality assurance (QA) or product department finds a bug, that means more people committing time to the fix. Once it hits customers, you’re talking about another production cycle as well as potential loss of business or trust.

  8. Tests help you smooth out development cycles and not “crunch.”

    Testing, refactoring, improving quality, and ultimately carrying a low amount of technical debt will help to prevent times when you need to move fast and “can’t help but break things.” That means long hours, delayed releases, and time away from whatever you enjoy outside of work.

  9. 9. Your feedback loop will be tighter.

    When you develop without tests, you’re increasing the amount of time between development and verifying that your code is working. With tests in place, your feedback loop can be reduced to a few seconds. Without them, you’re stuck with either assuming the code works or manually testing. If that takes five minutes every time (and gets longer as the program’s complexity grows), how often will you do it? Odds are, the tighter your feedback loop is, the more often you’ll verify that your code works, and the more confident you can be in making further changes.

The Many Ways of Testing

In this section, we’ll look at methods of testing. One important thing to note is that each testing method we are looking at has three stages: the setup, the assertion, and the teardown.

The taxonomy of tests varies by organization, industry, language, framework, and point in history. The categories here highlight the broader types that are interesting to us in refactoring, but this list is not exhaustive.  For instance, there are many variations of manual testing, and what we are calling “end-to-end” tests could be called integration tests, system tests, functional tests, or something else depending on the context.

We are mostly interested in tests that aid us in refactoring—that is to say, tests that protect and help to improve the quality of the software itself, rather than the experience of using it.

We consider a codebase to have full coverage when every code path is exercised by either unit tests, end-to-end tests, or ideally, both. It might seem overly picky to insist that every line is covered, but generally the worse the code is, the worse the coverage is, and vice versa. Practically speaking, 100% coverage is very hard to accomplish for many reasons, especially when you’re writing JavaScript and relying on external libraries. There are diminishing returns in confidence gained through more coverage as you approach 100% (or even “five nines”: 99.999%).

Testing is a tool to produce confidence. It is not the only tool. The original author of a codebase or a problem domain expert can derive confidence from other sources. Tests (along with code simplicity and, where appropriate, comments) are special sources of confidence because they allow the confidence to be transmitted along with the code. In any case, they are not the goal. Confidence is the goal. Tests are a practical way of creating specific types of confidence in the code that can be transferred to other team members or the future you.

For the sake of refactoring, end-to-end tests and unit tests are the most important of the types we’ll cover in this chapter.

Manual Testing

This was hinted at earlier in the chapter, but instinctively, everyone wants to test their code. If you’re working on a web app, that likely means just loading the page with the appropriate data objects in place and clicking around a bit. Maybe you throw a console.log() statement in somewhere to ensure variables have the expected values. Whether you call it “monkey testing” or “manual testing,” “making sure it works” or “QAing,” this testing strategy is useful for exploration and debugging.

If you’re faced with an undertested codebase, it’s a good way to experiment. This applies to the feature and debugging level of development as well. Sometimes, you just need to see what is happening. This is also a large component in spiking , the process of research that is sometimes needed before a “red/green/refactor” cycle can be entered.

Depending on which JavaScript you’re using (see Chapter 2 ), build/compiler errors can also be caught during this step.

Documented Manual Testing

One step toward automation from manual testing is to develop a testing/QA plan. The best manual tests are either temporary or well documented. Although you want to move on to feature tests and unit tests as quickly as possible, sometimes the fastest way to get a section of code “covered” is by writing a detailed set of steps to execute the relevant code paths. Although not automated, having a list (similar to what a QA team would have) can ensure that you are exercising the code in all the ways you need to, and makes the process less error prone by not relying on your memory. Also, it gives other members of your team a chance to contribute to and execute the plan as a “checklist.” This is handy to take some of the weight from a QA team, or fulfill that role if none exists.

If you find yourself lacking confidence in the code, with a big deploy looming and a dysfunctional or incomplete test suite, this is your best option. Documenting your code paths in text allows manual steps to be repeatable and distributed among team members.

Even if coverage is good, a QA department or developers filling that role may elect to manually run checks on a particular system if it is especially vital that it does not break (sometimes called a smoke test ) or contains complexity that is resistant to automated testing.

Approval Tests

This method is a bit tricky, but may work for some projects and team configurations. Sometimes, the outcome of code execution would be difficult to automatically assert. For instance, let’s say that you have an image processing feature on a website for automatically cropping and resizing an avatar. Setup is no problem: you simply feed it an image that you have on hand. But it could be difficult to write a simple assertion that proves the cropping tool worked well. Do you hardcode the bytes or pixels of the images for the desired input and output? That would make the tests very brittle, as they would break with every new image it crops. So do you skip testing altogether?

With an approval test, you automate the test setup and teardown, but the assertion (or “approval”) is left to human input. This test suite keeps a record of what output you have approved. When the test runs a second time, the same output will “pass,” and the other tests (that are new or have different results than the approved output) are added to the “unapproved” queue for human observation. When a member of the queue is approved, the new version of the output replaces or augments the memory of the old output (these can be files/database entries on the development machine or on a staging server). If everything is approved, then the code is assumed to be functioning correctly. If everything is not approved, the code gets the same treatment as it would for any failing test: it gets fixed, hopefully with a few regression tests that reproduce the specific conditions that caused the bug.

This process may work well when the output is something like an image, video, or audio file, where it’s difficult to write an assertion based on programmatically inspecting it. HTML may seem like a good fit for this type of testing, but often, end-to-end tests or unit tests are more appropriate if assertions are things like testing for text or an element on a page. Because you can use an HTML parser, or even a regular expression parser (most of the time) for HTML/CSS, that output is better tested through unit tests or end-to-end tests.

Just as manual tests are an organic process for testing as an individual, in some ways, approval tests are a natural way to test in a group. In any situation where a QA department, product owner, or designer is in a position to approve something’s output, an ad hoc approval test system is in place. Depending on the technical ability of the approver, he may be responsible for handling the setup programmatically, through a documented manual test, or by asking the developer for a demo.

The weaknesses of the ad hoc approval test system are that setup may be onerous for the approver, and that it may be difficult to remember what outputs were approved/rejected. This is not an insult toward the memory of anyone involved. Even if they are singularly focused on this process, if the team using the process changes, the departing members take all their knowledge of the old approvals with them.

But recognize that any attempt to framework-itize this process will produce something that looks different to an approver than what she might be used to. Keeping things simple for approvers probably means providing a list of URLs to be reviewed in the queue.

For the developer, there are nontrivial annoyances in setting up the queue, setting up each test, and providing some easy way for the approver to review.

Even though this process is popularly practiced by teams in an ad hoc way, there has been little innovation in the seemingly likely space of “approval test frameworks.” The questions raised by a system like this suggest some reasons why:

  • If development and approval are two distinct processes, where does the canonical list of approved/unapproved tests/checklists live?
  • Who is tasked with the “extra work” of translating product or design requirements into these lists?
  • Should the list of features be contained within the source code?
  • Should approval test failures (after a manual check) be integrated tightly enough to fail a test build?
  • If so, how can you avoid slowing down testing cycles?
  • If not, what is the feedback mechanism when someone rejects an approval spec?
  • Will there be a mismatch of expectations if developers see approval tests passing as the completion of a task?
  • What interaction, if any, should an approval test framework have with an issue/feature/bug tracking system?

It can be difficult enough for a process to be adopted when it is confined to a development team, but in the case of an approval test framework, everyone involved has to understand and agree to the answers to the preceding questions. Perhaps some Software as a Service product would be able to manage these concerns, but the preferred interfaces across different teams are varied and productized decisions about what types of processes to change with a tool like this are unlikely to make everyone happy.

Related: Acceptance Testing

There have been attempts to formalize “acceptance testing,” which rigorously mandates creation of specifications that correspond with user stories. If you are interested in this type of testing, Cucumber.js would be a framework to investigate.

Although it seems appealing, and it specifies a lot of uncertainty about approval tests, getting an internal cross-functional team or client on board may be more challenging than expected.

In the worst (but fairly likely) case, developers end up writing another entire layer of testing (rather than the client or “product owner”), but the client/product owner still requires the same level of process flexibility that the tests are intended to guard against.

Confusingly, some frameworks that are described as “acceptance test” frameworks do not insist on “English-like” syntax and do not imply a complex process that starts with a nondeveloper writing the spec in said English-like syntax. Instead, they provide high-level APIs for events like clicking and logging in, but these are clearly code, and not obscured by a layer of language that is converted into code.

These high-level APIs are useful for end-to-end tests, but be wary of frameworks that try to automate the actual acceptance of tasks. Requirements magically turning into code, and code magically fulfilling requirements, tends to actually be the magic that is software engineering, which isn’t really magic and probably involves humans talking to each other. Ta-da.

End-to-End Tests

Finally, the good stuff. These tests are meant to automate the actual interactions that a manual tester could perform with the interface provided to the end user. In the case of the web app, this means signing up, clicking on a button, viewing a web page, downloading a file, and so on.

For tests like these, code should be exercised in collaboration with other pieces of the codebase. Mocking and stubbing should be avoided except when absolutely necessary (usually involving the filesystem or remote web requests) so that these tests can cover the integration between different system components.

These tests are slow and simulate end users’ experience. If you want to split test suites into two, one fast and one slow, an end-to-end suite and unit test (covered next) suite are what you want.  These are also called high-level and low-level tests. As you’ll recall from the beginning of this chapter, “high-level” means to take a broader view and have your code be more concerned with an integration of parts, while “low-level” means being more focused on the details.

Unit Tests

Unit tests are fast and singularly focused on “units.” What is a unit ? In some languages, the answer would be “mostly classes and their functions.” In JavaScript, we could mean files, modules, classes, functions, objects, or packages. Whatever method of abstraction forms a unit, though, the focus of unit tests is on the behavior of the inputs and outputs of functions for each unit.

If we pretended that JavaScript’s ecosystem was simpler and just contained classes, this would mean testing the inputs and outputs inside that class, along with creating objects from the class.

“Private” Functions

It’s a bit of a simplification to say that JavaScript units, whatever those may be (classes? function scope? modules?), are split into “private” and “public” methods. In packages/modules, private methods would be the functions that are not exported. In classes and objects, you have explicit control over what is “private” in a sense, but that necessarily involves extra setup and/or awkward testing scenarios.

In any case, a popular recommendation is to test only public methods. This allows your public methods to focus on the interface of inputs and outputs, as the code for private methods will still be exercised when you run the public methods that make use of them. This leaves you with a bit of flexibility to change private methods’ implementation details, without having to rewrite the tests (as mentioned earlier, tests that break when an interface hasn’t changed can be called brittle ).

This is a good guideline in general, with tests also following the mantra “code to an interface, not an implementation,” but it doesn’t always line up with a priority of “code confidence.” If you can’t be confident in a public method without testing its implementation, feel free to ignore this advice. We’ll see an example of when this could happen in the next chapter when we deal with randomness.

In contrast to end-to-end tests, we’re only concerned with the independent behavior of functions of our units. These are low-level tests, rather than high-level tests. That means at integration points between units, we should feel free to mock and stub more liberally than with end-to-end tests. This helps us to keep the focus on the details, and leave the end-to-end tests tasked with the integration points. Additionally, if you avoid loading your entire framework and every package you use, as well as faking the calls to remote services and possibly the filesystem and database too, this test suite will stay fast, even as it grows.

Where Frameworks Can Let You Down

Frameworks often come with their own patterns of testing. These may relate to the directory that code lives in, rather than whether it is a unit test or an end-to-end test. This is unfortunate for two reasons. First, it encourages one test suite, rather than a fast suite (run frequently) and a slow suite (run somewhat often).

Division by app directory can also encourage tests that are part unit test and part end-to-end test. If you’re testing a signup in a web app, should you need to load the database at all? For an end-to-end test, the answer is probably yes. For a unit test, the answer is probably no. Having slow tests (end-to-end) and fast tests (unit) to differentiate this behavior would be ideal.

This division is eroded in part because colloquially, tests can be known as feature tests, model tests, services tests, functional tests, or something else, if the test directory mirrors the app directory. As an application grows, this could result in one big, slow test suite (with fast tests mixed in). Once you have one slow test suite, it is difficult to dig in and split it into necessarily slow tests and probably fast tests. Fortunately, your app’s structure may provide hints as to what folders should be fast and what folders should be slow (based on whether the files inside them tend to do high-level or low-level operations). Following that division, additional work is likely needed to remove loading dependencies of the potentially fast unit tests. As they are built without performance in mind, they are likely to load too much of the app, the database, and external dependencies.

One advantage to the default organization that a framework might provide is that tests may be easier to reason about, and to write to begin with. Although at some point this approach may be undesirable, having one test suite with good coverage is better than two with slightly better architecture but worse coverage.

All this is to say, solve the immediate problem, but look out for future problems as well. If you have bad coverage, that takes priority. If your test suite is so slow that no one will run it, a problem that you’re only likely to have as a result of many tests and good coverage, then focus your efforts on that problem.

Your test suite, just like any code, should be written to serve its primary purpose before performance tuning. Coverage and confidence come first, but if your suite gets bogged down to the point where it isn’t run frequently, then you must address the performance. You can do so by renting test running architecture online, parallelizing tests, splitting your tests into slow and fast suites, and mocking/stubbing calls to systems that are particularly slow.

Nonfunctional Testing

In the context of refactoring, nonfunctional testing does not directly contribute to accomplishing our code quality goals. Nor does it contribute to confidence that the code works. Nonfunctional testing techniques include:

  • Performance testing
  • Usability testing
  • Play testing
  • Security testing
  • Accessibility testing
  • Localization testing

Results of these types of tests contribute to new feature creation and issues (more broadly than what might initially be considered bugs) to fix. Is your game fun? Can people use your program? What about expert users? Is the first-time experience interesting? What about people with visual impairments? Will lax security policies lead to a data breach or prevent collaborations with partner companies or clients?

Unit and end-to-end testing will lead to coverage, confidence, and the chance to refactor, but they will not address these questions directly.

Try audio captcha sometime

Some audio captchas on websites are horribly difficult. But it’s worse than that. The experience often starts with being presented with an image of someone in a wheelchair, which certainly doesn’t apply to all people who are visually impaired. And the audio that follows is often disturbing and haunting as well as being difficult to parse. All in all, it’s a terribly unwelcoming and frustrating process.

In a conference talk, accessibility expert Robert Christopherson conducted an experiment with attendees using an audio captcha. He played it twice, and had everyone write down what they thought they heard, then compare it to the person next to them. Finally, he asked how many people had written down the same thing as their neighbor—zero out of about a thousand.

Ignoring nonfunctional testing will necessarily lead to ignoring some people, which is somewhere between mean and illegal. Nonfunctional testing is very important, but just not the focus of this book.

Nonfunctional testing, whether for accessibility or otherwise, is critical to the heart of a project. Because this book is focused strictly on technical quality, we can’t help but gloss over the many disciplines involved in nonfunctional testing, but we also can’t leave the topic without a recommendation to spend more time learning about these ideas. Not only that, but also consider that a team that is diverse, functionally, demographically, and in life experiences, can help to root out the most egregious problems quickly and make the nuances more clear.

All this said, these testing techniques tend to generate tasks (bugs/features/enhancements) that will need attention in addition to what the obvious product road map indicates. This means more code changes and potentially more complexity. You want to meet that complexity with confidence, just as you would with mainline product features. The confidence to be flexible, fix bugs, and add features comes from testing.

Other Test Types of Interest

We’ll cover these in detail in the next chapter, but this classification concerns different ways that your tests may interact with the implementation code. All of these three types may be either high-level or low-level:

Feature tests

These are the tests that you write for new features. It is helpful to write the tests first (use test-driven development, or TDD), as will be demonstrated in the next chapter.

Regression tests

These tests are intended initially to reproduce a bug, after which changes are made to the implementation code in order to fix the bug. This guarantees coverage so that that bug does not pop up again.

Characterization tests

You write these for untested code to add coverage. The process begins with observing the code through the test, and ends with unit or end-to-end tests that work just as if you had written a feature test. If you want to follow TDD, but the implementation code is already written (even if you just did it), you should consider either writing this type of test or temporarily rolling the implementation code back (or commenting it out) in order to write the test first. This is how you can ensure good coverage.

Tools and Processes

Hopefully at this point, you’re totally on board with the “why” behind testing, and understand how unit and end-to-end tests form the core to being confident in your code.

There is one last problem we need to address in this chapter: testing is hard . We already wrote the code, and now we have to do extra work to write the code that uses it in a structured and comprehensive way? That’s frustrating (and also backward if you’re doing TDD, but we’ll get to that in a few short pages).

The larger problem is that quality is hard . Fortunately, there’s more than just advice on how to do this: there are processes and tools as well as a good half-century’s worth of research on how to encourage quality software.

Not all of these tools and processes are great for every project and every team. You might even spot an occasional lone-wolf programmer who avoids process, tools, and sometimes testing altogether. She might be deeply creative and prolific, to the point where you see her and wonder if this is how all software should be developed.

In complex software, maintained by teams of coders of varying skill levels, responsible for real deadlines and budgets, this approach will result in technical debt and “siloed” information that is not well understood by the whole team. Quality processes and tools scale up with complexity of projects and teams, but there’s really no one-size-fits-all situation.

Processes for Quality

Coding standards and style guides

The simplest process to use in order to help with test coverage and quality is for a team to adopt certain standards. These typically live in a style guide and include specifics like “Use const and let instead of var ” as well as more general guidelines like “All new code must be tested” and “All bug fixes must have a test that reproduces the bug.” One document may cover all the systems and languages that a team uses, or they could be broken out into several documents (a CSS style guide, a frontend style guide, a testing style guide, etc.).

Developing such a guide collaboratively with team members, and revisiting it from time to time, can make it flexible enough to adopt to changing ideas of what “good” means for the team. Having this guide in place provides a good foundation for the other processes covered here. Also, in an ideal world, most of this style guide is also executable, meaning that you have the ability to check for a large class of style guide violations very easily.

The term “style guide” may also refer to a design document describing the look and feel of the site. Aspects of this may even be in an external “press kit”–type form with instructions (“Use this logo when talking about us,” “Our name is spelled in ALL CAPS,” etc.) These are distinct documents. Putting documents like these in the same place as the coding style guide is not recommended.

Developer happiness meeting

Another lightweight quality-focused process worth considering is a weekly, short meeting sometimes referred to as a developer happiness  (this name may not be well received by noncoders in the organization), engineering quality , or technical debt meeting. The purpose of the meeting is to recognize areas in the codebase that have quality problems worth addressing. If product managers tightly control the queue of upcoming tasks, then this process enables one of the developers to perpetually make the case to them for adding a given task to the queue. Alternatively, developers or product managers may allocate a weekly budget for these types of tasks.

However the tasks are given priority, this process allows for things like speeding up the test suite; adding test coverage to a legacy module; or refactoring tasks to be addressed in a way that doesn’t surprise anyone, maintains a quality focus, and allows the worst technical debt to be surfaced, widely understood, and then paid off.

Pair programming

Pairing , aka pair programming , is a simple idea, but implementing it in a team can be difficult. Basically, two programmers tackle a problem, side-by-side, with one person running the keyboard (“driving”) while the other watches the screen and sometimes has an additional computer available for research and quick sanity checks without tying up the main development machine. Typically the “driver” role is passed back and forth, sometimes at regular, predetermined intervals.

Pairing can lead to higher quality because it helps catch small bugs, even just typos, right away. Additionally, questions about quality (“Is this too hacky?” or “Should we test this as well?”) come up frequently. Openly discussing these details can lead to more robust code and higher test coverage. Another benefit is that information about the system is held by at least two people. Not only that, but it helps other knowledge, from algorithms to keyboard shortcuts, to spread through an organization.

Knowledge sharing, focus, high-quality code, and company—what’s the downside? First, like with other quality-based initiatives, it can be difficult to justify the upfront expense. “Two programming ‘resources’ are working on one task. What a waste!” Second, this process demands total focus, and it can actually be quite exhausting for the programmers. For this reason, pairing is often seen coupled with use of the “pomodoro” technique, where focus is mandated in 25-minute increments, with 5-minute breaks in between. Third, this process can feel insulting and frustrating to programmers (especially high performers) who think their output is slowed by it. Often this happens when there is a large gap in experience between the pairing partners. Although this difference in skill potentially benefits the team most by allowing the greatest amount of knowledge transfer, not every programmer wants to act as a mentor. If it’s a priority to keep pair-averse individual contributors happy and on staff, a teamwide mandate might be too aggressive of an approach.

Experimenting with pairing and getting feedback is a good idea, but teams tend to pair either very often or very rarely. Without a mandate or at least a genuinely supportive attitude from the team and management, despite its benefits, a situation can develop where those who would pair are reluctant to do so for fear of being seen as ineffective on their own. Skepticism of the process by pair-averse team members or managers will feed this reluctance. Then “pairing” takes on a new meaning, where people “pair” when they’re stuck. Thus a cycle forms where pairing is stigmatized. So while pairing isn’t “all or nothing,” it likely is “mostly or barely.”

A Note on “Resources”

When people (usually project/product managers) refer to team members in the design, development, or any other department as “resources,” as in “We need more programming resources on this project,” or “I need a resource for my project,” try giving them a quizzical look and saying “What? Oh...You mean people ?”

There are two problems here. First, hopefully, your team consists of programmers with diverse skills and experiences, and thinking of them as interchangeable units is not a good start to ensuring a project is well executed. Second, defining people (especially to their faces) strictly by their function is somewhere between unprofessional and mechanistically dehumanizing.

Three (not mutually exclusive) variations on pairing worth noting are TDD pairing , remote pairing , and promiscuous pairing . With TDD pairing, the driving role tends to alternate with the first person writing a test, and the second person implementing the code to make the test pass. In remote pairing, people not in the same physical location share their screens along with open audio and video channels. In promiscuous pairing , as opposed to dedicated pairing , the pairs of people are rotated on a day-by-day, week-by-week, sprint-by-sprint, or project-by-project basis.

Code review

Another technique that helps ensure quality by putting another set of eyes on the code is code review . Through this process, when code is “finished,” it is put into a review phase where another programmer looks through it, checking for style guide violations, bugs, and comprehensive test coverage. This may also be combined with a QA pass from the developers (especially on teams without a QA department), where the reviewing programmer manually runs the code and compares it with the task description (or more formally, acceptance criteria ).

While pair programming and code review will not directly help overcome a dislike of testing, they will provide opportunities to focus on testing and quality. Enough of these experiences should help provide a more nuanced perspective on testing than that reflected by the quotes used to start off this chapter. Both processes give opportunities to establish norms and reinforce culture.

Test-driven development

If you have the basics of testing down, test-driven development (TDD) can produce quality code with good test coverage. The downside is that it is a significant departure from a process of testing after the implementation code is written. The upside is that TDD, through the red/green/refactor cycle, can provide guidance throughout development. Additionally, if TDD is followed strictly, implementation code is written only in order to get a passing test. This means that no code is written that does not have coverage, and therefore, no code is written that cannot be refactored.

One challenge to a coder using TDD is that sometimes it is not obvious how to test, or even write the implementation code to begin with. Here, an exploratory phase known as spiking is suggested, where the implementation code is attempted before the tests are written. Strict TDD advocates will advise deleting or commenting out this spike code once the coder understands the task well enough to write tests and implement them, à la the normal red/green/refactor cycle.

A term that you’ll often see alongside TDD is BDD (behavior-driven development). Basically, this process is extremely similar to TDD, but is done from the perspective of the end user. This implies two main points of importance. First, the tests tend to be high-level, end-to-end tests. Second, inside the red/green/refactor cycle of BDD end-to-end tests, there are smaller red/green/refactor cycles for TDD’d unit tests.

Let’s take a look at a slightly complex diagram of a red/green/refactor cycle ( Figure 3-1 ).

Figure 3-1. A red/green/refactor cycle

Whoa. Okay, so this might look a little crazy, but there are only a few complications here, and this should help you if you’re wondering what part of the red/green/refactor cycle you are in.

Starting at the top left, we write a failing test, which puts us in a red state. We have three possibilities from there (one failing test). We could follow the arrow to the right (top-middle red state) and write another failing test (then we would have two). Or, if possible, we could follow the long arrow down to the green state (implement the test). The most complicated possibility exists when we can’t implement the test to make it pass right away. In that case, we follow the short arrow down, where we meet another cycle just like this one. Assume we’re stuck there for now, but we’re always free to create new failing tests in any cycle that we’ve initiated.

If any tests (at any level) are in the green state in the middle, we can do one of two things: either refactor, or call it done and consider this test and code complete (leave the cycle). When we start refactoring, we can either keep refactoring or consider this test and code complete (leave the cycle).

When all the tests are complete, the arrows can all leave the cycle. If we’re in an inner cycle, that means we move into the green phase of the outer cycle. If we’re in the outer cycle, and we can’t think of any more tests to write (no more reds to tack on to the top row), then we’re done.

One subtlety in this process worth noting is that creating a new red test after a green test is recommended only after you have at least considered a refactoring phase. If you move on right away, there is no clear indication that more work is to be done. By contrast, if you have just refactored something, then you’re free to move on. Similarly, if you have written a failing test (red state), then if you write another test case, your test framework will still let you know that there is more work to be done on the first one, so you won’t get lost there.

Moving on from the diagram, here is a concrete example of a TDD cycle containing another TDD cycle:

  1. Failing (red) high-level test is written: “A customer can log in.”

    1. Failing low-level test is written: “Route ‘/login’ returns 200 response.”
    2. Routing code is written to pass the low-level test. We can refactor this code written on the inner cycle now.
    3. The high-level test is still failing, so a new failing low-level test is written: “The form post route at ‘/login_post’ should redirect to ‘/’ for valid email and password.”
    4. Code is written to handle successfully posting the email/password and returning the logged-in home page. This inner cycle test is passing, so we can refactor this code written on the inner cycle now.
  2. Now both the second low-level test and the high-level test are passing.

  3. Once everything in our outer cycle test is green, we’re free to refactor the outer cycle as we see fit. And we have two levels of testing to ensure our code continues to behave.

For the purposes of refactoring, using a methodology like BDD doesn’t really matter. What matters is that you have good coverage in your code, preferably from unit tests and end-to-end tests. If those were created in a “test first” manner via TDD or BDD, that’s fine. But the aspect of testing from the end users’ perspective through BDD is not critical. It’s possible to create high-level tests with good coverage that don’t test from this perspective and that aren’t written before the implementation code.

Quality Processes as Team and Personal Branding

You will often see development methodologies and quality-enhancing techniques used as social proof. Job seekers add them to their résumés, hiring pages display them on job listings, and top consultancies build their brands around them.

Although day-to-day there may a focus on “getting things done” (potentially to the detriment of quality), being comfortable with these techniques and tools means access to better employment opportunities, be they with companies or clients.

Tools for Quality

Moving on to tools for testing...this could be a book unto itself. Though individual frameworks and tools rise and fall in popularity, knowing what types of tools are available will remain useful. Sometimes, GitHub or npmjs stars are a good proxy for quality and popularity. Searching for “js <tooltype>” (e.g., “js test coverage”) with your preferred search engine usually returns decent results. It’s best to learn one or two versions of each of these tools well, but with JavaScript’s open source package development being as expansive as it is, be prepared to frequently adapt to new but similar tools.

Version control

Before any other tool is mentioned (in case you missed it in Chapter 1 ), it is critical that your project is under version control, preferably with backups somewhere other than just your computer. If lack of testing should produce skepticism rather than confidence, lack of version control should produce uneasiness, if not terror. Version control, with a backup online (as of this writing, Git + GitHub is recommended), ensures your code doesn’t completely disappear. No amount of quality in the code matters if it can just get wiped out. Additionally, many of the tools covered here rely on versioned software for integration and to demonstrate progress.

Test frameworks

These vary significantly based on what JavaScript you are using (see Chapter 2 ), and how many tools you want bundled together. In general, these allow you to specify test cases in a file (or many) and have a command-line interface that you can use to run the test suite. A test framework may include many of the tools listed next as well. Some frameworks are specific to the frontend or backend code. Some are specific to the JavaScript framework. Some are specific to high-level, low-level, or acceptance tests. They will usually dictate how your test files are written as well as providing a test runner. The test runner will execute the suite (often allowing targeting of a specific directory, file, or individual test case), and output errors and failures of the run. It will also likely be responsible for the setup and teardown phases of your test run. Besides loading code, this can also mean putting the database in a particular state (“seeding” it) before the test run, and then resetting it afterward (as your tests may have created/deleted/changed records).

In the next chapter, we use some of the more basic features of the Mocha test framework. In Chapter 9 , we’ll also be trying out a more lightweight framework called Tape.

Assertion/expectation syntax libraries

These are usually meant to work with particular testing frameworks and often come bundled with them. They are what enable you to assert that a given function returns “hello world” or that running a function with a given set of inputs results in an error.

Assertion libraries can be unnecessarily complicated. Chapter 4 introduces a simple assertion and characterization testing library called wish.

Domain-specific libraries

Examples of these include database adapters and web drivers (to simulate clicks and other website interactions). These may be bundled into a JavaScript framework or testing framework. Often, they come with their own assertion/expectation syntax that extends the testing framework.

Factories and fixtures

These tools are responsible for creating database objects either on demand (factories) or from a file specifying data (fixtures). These libraries are sometimes associated with the word fake or faker . You’ll find these useful if your tests require a lot of code to set up.

Mocking/stubbing libraries

These are sometimes associated with the terms mocks/mocking , stubs/stubbing , doubles , and spies . Mocks and stubs both allow you to avoid calling a certain function in your tests, while mocks also set an expectation (a test) that the function is called. General mocking/stubbing functionality is usually included as part of a testing framework, but there are also more specific mocking/stubbing libraries that are not. These may stub out whole classes of function calls, including calls to the filesystem, the database, or any external web requests.

Build/task/packaging tools

The JavaScript ecosystem has a ton of tools for gathering code together, transforming it, and running scripts (custom or library-defined). These can be dictated by a JavaScript framework, and you might have some that overlap in your project.

Loaders and watchers

If you’re running the test suite frequently, which is essential to having a tight feedback loop, loading your whole app/program before every run can slow you down significantly. A loader can speed up the process by keeping your app in memory. This is often paired with a watcher program that executes your test suite when you save a file. The feedback loop can be tightened even further when the watcher script intelligently only runs the tests relevant to the saved file.

Test run parallelizers

Sometimes built into loaders/task runners or test frameworks, these tools make use of multiple cores on your machine, parallelizing the test run and speeding up the execution of the test suite. One caution here worth noting is that if your application is heavily dependent on side effects (including using a database), you may see more failures when tests produce state that conflicts with other tests.

Continuous integration (CI) services

These are online services that run your test suite on demand or upon events like committing to the shared version control repository, sometimes restricted to particular branches. These often make use of parallelization (and offer overall performance) beyond what you could accomplish on your personal machine.

Coverage reporters

In order to know if code is safe to refactor, it is essential to know that the code is sufficiently covered by tests. Whether or not you are able to determine coverage without actually running the test suite (and consequently exercising the code) is an interesting academic question of dynamic versus static analysis, but fortunately, coverage tools that determine coverage by running the test suite are abundant. These can be run locally, but are often paired with CI systems.

Mutation Testing

If you’re interested in other possibilities using dynamic analysis, which coverage tools make use of, you might want to check out mutation testing .

This topic can run a bit deep, but basically a tool runs your test suite with a mutated codebase (most easily by changing test inputs, e.g., a string input where a boolean was expected) and fails when your tests pass in spite of the mutated code.

This can allow you to find cases where tests don’t actually require the code to be as it is. That may mean that the code is not exercised, but it also could mean that the normal input is meaningless in the context of the test. For example, if a parameter to a function is used in a way that is so general that various mutated inputs would work just as well, it suggests that even if coverage shows a line of code as being run, the code is not sufficiently exercised. At best, you may just be relying on type coercion in JavaScript’s case.

Two warnings apply here. First, mutation testing relies on multiple variations on your normal test suite, so it will tend to be slow. Second, it may break your code in unexpected ways and complicate the teardown phase of your test—for example, by doing anything from leaving your test database in an unexpected state to actually changing the code in your files. Check your code into version control and back up your database before you run something this aggressive and unpredictable.

Style checkers, aka linters

Most quality tools don’t require dynamic analysis. They can inspect files without executing the code to look for many types of errors or stylistic violations. These checks are sometimes run locally as discrete scripts or through online services after code is committed to a shared repository. For a tighter feedback loop, these checks can often be integrated in a programmer’s IDE or editor. You can’t do any better than getting notifications of mistakes immediately after you write them. Sometimes these are called linters . At best, these style checkers you have in place serve as an executable style guide.

Debuggers/loggers

Sometimes, during a spike (writing exploratory, temporary code without testing), a tricky test case, or a manual test, it may be unclear what values variables have, what functions are outputting, or even whether a certain section of code is running. In these cases, debuggers and loggers are your friends. At the point in the file where the confusion lies, either in your test or your implementation code, you can add a logging statement or set a debugging breakpoint . Logging will sometimes give you the answer you need (e.g., “this function was reached” or “this file was loaded”), but debuggers offer the chance to stop execution of the code and inspect any variable or function call you want.

Staging/QA servers

It can be difficult to simulate production to the level needed on your local development machine. For this reason, servers (or instances/virtual machines) that are as similar as possible to production are often used with a database that has a sanitized but representative version of production data.

Note

If these processes and tools seem overwhelming, don’t worry. When you need them, they can be useful, and if you don’t, you can usually avoid them. It’s good to experiment with new tools like these on hobby projects, but if you go overboard, you’ll end up spending more time configuring everything to work together than you will actually doing the project!

Wrapping Up

So now we have a good overview of what testing is, as well as why it’s useful and completely essential to refactoring. In the next chapter, we’ll cover how to test your codebase, regardless of what state it’s in.