Svelte with Test-Driven Development - Daniel Irvine - E-Book

Svelte with Test-Driven Development E-Book

Daniel Irvine

0,0
25,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Build robust and performant applications by developing SvelteKit applications using automated testing and TDD techniques, including unit and end-to-end testing, custom matchers, component mocking, and authentication


Purchase of the print or Kindle book includes a free PDF eBook


Key Features


Understand and master the test-driven development (TDD) workflow


Explore the principles of unit testing with Vitest and end-to-end testing using Playwright and Cucumber.js


Leverage practical examples of unit tests covering a range of SvelteKit framework features


Book Description


Svelte is a popular front-end framework used for its focus on performance and user-friendliness, and test-driven development (TDD) is a powerful approach that helps in creating automated tests before writing code. By combining them, you can create efficient, maintainable code for modern applications. Svelte with Test-Driven Development will help you learn effective automated testing practices to build and maintain Svelte applications.


In the first part of the book, you’ll find a guided walkthrough on building a SvelteKit application using the TDD workflow. You’ll uncover the main concepts for writing effective unit test cases and practical advice for developing solid, maintainable test suites that can speed up application development while remaining effective as the application evolves. In the next part of the book, you’ll focus on refactoring and advanced test techniques, such as using component mocks and writing BDD-style tests with the Cucumber.js framework. In the final part of the book, you’ll explore how to test complex application and framework features, including authentication, Svelte stores, and service workers.


By the end of this book, you’ll be well-equipped to build test-driven Svelte applications by employing theoretical and practical knowledge.


What you will learn


Create clear and concise Vitest unit tests helping the implementation of Svelte components


Use Playwright and Cucumber.js to develop end-to-end tests that simulate user interactions and test the functionality of your application


Leverage component mocks to isolate and test individual components


Write unit tests for a range of Svelte framework features


Explore effective refactoring techniques to keep your Svelte application code and test suites clean


Build high-quality Svelte applications that are well-tested, performant, and resilient to changes


Who this book is for


This book is an essential guide for Svelte developers seeking to enhance their development process by learning the TDD workflow and its application. Whether you are an experienced developer or new to automated testing, this book helps you gain a practical approach to improving your workflow. The examples are written in JavaScript, making them accessible to all developers, including TypeScript developers.


Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 249

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Svelte with Test-Driven Development

Advance your skills and write effective automated tests with Vitest, Playwright, and Cucumber.js

Daniel Irvine

BIRMINGHAM—MUMBAI

Svelte with Test-Driven Development

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Bhavya Rao

Content Development Editor: Abhishek Jadhav

Technical Editor: Simran Ali

Copy Editor: Safis Editing

Project Coordinator: Sonam Pandey

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Jyoti Chauhan

Marketing Coordinator: Nivedita Pandey

First published: July 2023

Production reference: 1060623

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-83763-833-8

www.packtpub.com

Contributors

About the author

Daniel Irvine is a software consultant based in London. He works with a variety of languages, including C#, Clojure, JavaScript, and Ruby. He’s a mentor and coach for developers and runs TDD and XP workshops and courses. When he’s not working, he spends time cooking and practicing yoga. He co-founded the Queer Code London meetup and is an active member of the European Software Craft community. He is the author of Mastering React Test-Driven Development (Packt), now in its second edition, and Build Your Own Test Framework (Apress). He can be contacted through his website: www.danielirvine.com.

I want to thank my developer friends and colleagues at Mindful Chef, in particular Aleksandra Sezer, Brendan Murphy, James Edward-Jones, James Graham, James Teale, Mark McDermid, Tito Molina, and Zack Xu, who all assisted me during the authoring process. The team at Packt have been brilliant, as usual, giving me exactly the support I needed to complete the book. Thanks in particular to Bhavya Rao, Sonam Pandey, and Abhishek Jadhav. I look forward to our next project!

About the reviewer

Aakash Goplani is a JavaScript developer with eight years of rich experience in developing web applications using Angular and Svelte. Aakash is also experienced in developing hybrid mobile applications using Ionic. Apart from web development, Aakash has also worked on content management systems using Oracle WebCenter Sites.

Table of Contents

Preface

Part 1: Learning the TDD Cycle

1

Setting up for Testing

Technical requirements

Creating a new SvelteKit project

Installing and running Playwright

Running Vitest

Preparing your development environment for frequent unit testing

Choosing your editor

Creating a shell alias

Changing the test runner to report each test name

Watching the test fail

Configuring support for Svelte component tests

Installing jsdom and testing library helpers

Writing a test for the DOM

Writing a first Svelte component test

Ensuring the DOM is cleared after each test run

Restoring mocks automatically

Optional configuration

Configuring Prettier’s print width

Reducing the tab width in the Terminal

Summary

2

Introducing the Red-Green-Refactor Workflow

Technical requirements

Understanding the Red-Green-Refactor workflow

Thinking ahead with some up-front design

The Birthdays application

Writing a failing test

Making it pass

Repeating the process

Refactoring the tests

Cleaning up warnings

Adding a third test to triangulate

Adding styles to the component

Summary

3

Loading Data into a Route

Technical requirements

Using Playwright to specify end-to-end behavior

Writing the test and watching it fail

Understanding the difference between Vitest tests and Playwright tests

Deciding an approach to make the end-to-end test pass

Test-driving the load function

Test-driving the page component

Summary

4

Saving Form Data

Technical requirements

Adding a Playwright test for data input

Test-driving a SvelteKit form

Adding the form component to the page component

Test-driving a SvelteKit form action

Building a factory for the FormData objects

Building a Vitest test suite for the form action

Summary

5

Validating Form Data

Technical requirements

Adding a Playwright test for validating form errors

Displaying SvelteKit form errors

Passing the form data through the page component

Validating data in the form action

Clearing the data store between tests

Summary

6

Editing Form Data

Technical requirements

Planning the path ahead

Adding a Playwright test for editing form data

Evolving the repository to allow ID lookup

Updating the form action to handle edits

Replacing items in the repository

Protecting against unknown identifiers

Updating return values to include identifiers

Updating the list page with a new edit mode

Adding a toggle mode to the page

Summary

Part 2: Refactoring Tests and Application Code

7

Tidying up Test Suites

Technical requirements

Using page object models in Playwright tests

Extracting an action helper

Extracting a factory method for creating data objects

Summary

8

Creating Matchers to Simplify Tests

Technical requirements

Test-driving the pass or failure of an expectation

Understanding matcher structure

Testing a matcher

Writing the toBeUnprocessableEntity matcher

Providing extra information in failure messages

Implementing the negated matcher

Updating existing tests to use the matcher

Summary

9

Extracting Logic Out of the Framework

Technical requirements

Migrating tests with a test todo list

Porting tests from the form action

Duplicating form validation behavior in the repository

Extracting common methods

Summary

10

Test-Driving API Endpoints

Technical requirements

Creating a service test with Playwright

Adding an API endpoint for retrieving data

Adding an API endpoint for saving data

Adding an API endpoint for updating data

Summary

11

Replacing Behavior with a Side-By-Side Implementation

Technical requirements

Updating the route loader to use the API

Updating the page form action to use the API

Using a server hook to seed sample data

Summary

12

Using Component Mocks to Clarify Tests

Technical requirements

Avoiding component mocks

Avoiding overtesting using TDD

Using hand-rolled component stubs

Rendering all props within a component stub

Checking the ordering of component instances

Dealing with complex props

Dispatching component events

Using a component mock library

Installing the library

Writing tests using the componentDouble function

Summary

13

Adding Cucumber Tests

Technical requirements

Creating the feature file

Setting up a Playwright world object

Implementing the step definitions

Summary

Part 3: Testing SvelteKit Features

14

Testing Authentication

Technical requirements

Testing authentication with Playwright

Creating an auth profile for dev and test modes

Writing tests for login

Updating existing tests to authenticate the user

Testing authentication with Vitest

Defining a session factory

Updating existing tests for page load functions

Updating existing tests for form actions

Summary

15

Test-Driving Svelte Stores

Technical requirements

Designing a store for birthdays

Writing tests for reading store values

Writing tests for updating store values

Summary

16

Test-Driving Service Workers

Technical requirements

Adding a Playwright test for offline access

Implementing the service worker

Summary

Index

Other Books You May Enjoy

Preface

What excites me about Svelte? Its simplicity, elegance, and pragmatic design ethos. Its growing success in the marketplace suggests that other programmers feel the same way too. I’m not surprised by this. When we write software for the JavaScript ecosystem, we have a choice: we can either accept and be consumed by the complexity of its primary constituents (React, Node.js, webpack, Babel, and so on) or we can actively seek out the marginalized products and processes that aim to simplify our work.

It’ll be no surprise to you that I place Test-Driven Development (TDD) firmly in this second camp. Because without it, what you have is a development workflow that largely consists of chasing bugs and carrying a lot of context in your head. This is always what I think of as the bad old days.

When I first started programming as a youngster, I remember the infuriating experience of debugging – writing some code, trying it out, finding bugs, and struggling for hours to figure out where the errors were hidden in my code. It seemed like a natural part of programming: devoting a large portion of my time to debugging. And this carried through into my first job as a C++ desktop application developer. (It wasn’t long before I discovered TDD and how it could help me have a simpler, quieter, calmer life.)

Then there’s the mental context you need when you plan out a grand design for the next feature you’re about to implement. You have to know where you’re at, what you’ve done, and what’s next, and do your best to not stray from the path. That’s hard when you’re being derailed by debugging and other distractions.

Sure, you can write a to-do list or keep a diary, but why not write some automated tests instead? They not only remind you where you’re at but they check for bugs, too.

That is essentially the idea behind TDD.

And if you like Svelte because it simplifies your life and makes you feel like you’re swimming rather than wading through mud, I think you’ll also like TDD. This book shows you the how and why of Svelte with TDD. I hope you enjoy it. Thanks for reading!

Who this book is for

If you’re a Svelte programmer, this book is for you. I aim to show you how TDD can improve your work. If you’re already knowledgeable about TDD, I hope there’s still a lot you can learn from comparing your own process with mine.

If you don’t already know Svelte, but you’re familiar with any modern frontend framework such as React, you should be able to follow along and pick things up as you go. TDD is a wonderful platform for explaining new technologies, and it’s entirely plausible that you’ll be able to pick up Svelte simply by following this book.

What this book covers

Chapter 1, Setting up for Testing, covers the SvelteKit package and configuring your development environment for effective TDD work with both the Vitest and Playwright test runners.

Chapter 2, Introducing the Red-Green-Refactor Workflow, shows how the basic TDD process works, and discusses why it’s useful. It introduces the Vitest test runner for writing unit tests.

Chapter 3, Loading Data into a Route, demonstrates how to load data into a Svelte page component using TDD. It introduces the Playwright test runner for writing end-to-end tests.

Chapter 4, Saving Form Data, shows how to implement a basic HTML form along with its submit action.

Chapter 5, Validating Form Data, adds form validation rules to the form built in Chapter 4.

Chapter 6, Editing Form Data, shows how TDD can be used to evolve a system design, by modifying the form to work in edit mode.

Chapter 7, Tidying up Test Suites, switches focus to look at techniques for better testing, starting with a look at how test suites can be kept neat and tidy.

Chapter 8, Creating Matchers to Simplify Tests, explains an advanced technique for managing the complexity of test suites: creating and using expectation matcher functions.

Chapter 9, Extracting Logic Out of the Framework, discusses how you can make your application design more testable by moving logic out of framework-controlled modules.

Chapter 10, Test-Driving API Endpoints, looks at how you can use TDD to implement API calls.

Chapter 11, Replacing Behavior with a Side-By-Side Implementation, shows how TDD is useful even when faced with complex refactoring exercises.

Chapter 12, Using Component Mocks to Clarify Tests, introduces the most complex piece of frontend automated testing: component mocking.

Chapter 13, Adding Cucumber Tests, introduces the Cucumber test framework and shows how it can be applied to a SvelteKit project.

Chapter 14, Testing Authentication, shows an approach to writing both unit and end-to-end tests for authentication libraries.

Chapter 15, Test-Driving Svelte Stores, provides a brief look at how Svelte stores can be effectively tested.

Chapter 16, Test-Driving Service Workers, shows how to write automated tests for service workers, as supported by the SvelteKit framework.

To get the most out of this book

There are two ways to read this book.

The first is to use it as a reference when you are faced with specific testing challenges. Use the index to find what you’re after and move to that page.

The second, and the one I’d recommend starting with, is to follow the walk-throughs step by step, building your own code base as you go along. The companion GitHub repository has a directory for each chapter (such as Chapter01) and then, within that, two directories:

Start, which is the starting point for the chapter; you should start here if you’re following along.Complete, which contains completed solutions to all the exercises.

You will need to be at least a little proficient with Git; a basic understanding of the branch, checkout, clone, commit, diff, and merge commands should be sufficient.

Take a look at the README.md file in the GitHub repository for more information and instructions on working with the code base.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Svelte-with-Test-Driven-Development. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/GD8Lg.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “We can start with a test that specifies what this Birthday component will do with its name prop.”

A block of code is set as follows:

import { describe, it, expect } from 'vitest'; import {   render,   screen } from '@testing-library/svelte'; import Birthday from './Birthday.svelte';

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

describe('Birthday', () => {   it('displays the name of the person', () => {     render(Birthday, { name: 'Hercules' });   }); });

Any command-line input or output is written as follows:

mkdir birthdays cd birthdays npm create svelte@latest

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “The user clicks the Save button.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Svelte with Test-Driven Development, we’d love to hear your thoughts! Please select https://www.amazon.in/review/create-review/error?asin=1837638330 for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781837638338

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Learning the TDD Cycle

The first part introduces the Test-Driven Development (TDD) workflow and explains how you can use it to build Svelte applications.

This part has the following chapters:

Chapter 1, Setting up for TestingChapter 2, Introducing the Red-Green-Refactor WorkflowChapter 3, Loading Data into a RouteChapter 4, Saving Form DataChapter 5, Validating Form DataChapter 6, Editing Form Data

1

Setting up for Testing

Back when you were a young schoolchild, you probably learned to write by using a pencil on paper. Now that you’re older, it’s likely you prefer pens. For learners, pencils have a distinct advantage over pens in that mistakes are easy to correct, and when you first start writing out letters and words, you will be making a lot of mistakes. Pencils are also safer for small children – no caps or messy ink to worry about.

But pencils remain a valid writing instrument, and you might still have a personal preference for pencils over pens. The pencil is a perfectly good tool for the job.

Test-Driven Development (TDD) is a tool that can serve you in a similar way. It’s a great way to learn and grow as a developer. Many experienced developers prefer it for their day-to-day work over any alternative.

In this chapter, you’ll configure a work environment that’s designed to help you get the most out of TDD techniques. Since TDD asks you to do a bunch of small repetitive tasks – writing tests, running tests, committing early and often, and switching between test code and application code – it’s important that each of those tasks can be done easily and quickly.

It follows that an important personal discipline to cultivate is that of objectively critiquing your development tools. For every tool that you use, ask yourself this: is this tool serving me well? Is it easy and quick to use?

This could be your Integrated Development Environment (IDE), your operating system, your source code repository, your note-taking program, your time management utilities, and so on. Anything and everything you use in your day job. Scrutinize your tools. Throw away whatever isn’t working for you.

This is a very personal thing and depends a lot on experience and individuality. And your preferences are likely to change over time, too.

I often reach for very plain, simple, keyboard-driven tools that work for me consistently, regardless of the programming language I’m working in, such as the text editor Vim. It doesn’t offer any knowledge about the JavaScript programming language or the Svelte framework, but it makes me extremely effective at editing text.

But if you care about learning JavaScript or program design, then you might prefer an IDE that gives you JavaScript auto-complete suggestions and helpful project assistance.

This chapter walks through the setup of a new SvelteKit project and highlights all the individual choices you’ll need to make, and the additional extras you’ll need in order to practice effective TDD.

It covers the following topics:

Creating a new SvelteKit projectPreparing your development environment for frequent test runsConfiguring support for Svelte component testsOptional configuration you may want to try

By the end of the chapter, you’ll know how to create a new Svelte project that is ready for test-driven feature building.

Technical requirements

The code for the chapter can be found online at https://github.com/PacktPublishing/Svelte-with-Test-Driven-Development/tree/main/Chapter01/Start.

You will need to have a recent version of Node.js installed. See https://nodejs.org for instructions on how to install and update Node.js for your platform.

Creating a new SvelteKit project

In this section, you’ll use the default method for creating a new SvelteKit project, which uses the npm create command. (For reference, you can also check the official documentation at https://kit.svelte.dev/docs/creating-a-project.)

The project we are building is called Birthdays and the npm package name is birthdays. It will be introduced properly in Chapter 2, Introducing the Red-Green-Refactor Workflow.

SvelteKit 1.0

These instructions were valid at the time of writing, for SvelteKit 1.0. It’s likely things will improve in time, so you may find some of the later instructions will become unnecessary or may no longer work. Check the book’s GitHub repository for the most up-to-date instructions.

For now, we’ll concentrate on the mechanics of building a new project:

Start by opening a Terminal window in your usual work location (for me, this is ~/work on my Mac). Then type the following commands:mkdir birthdayscd birthdaysnpm create svelte@latest

If this is the first Svelte project you’ve created, you’ll be presented with the following message from npm:

Need to install the following packages:  [email protected] to proceed? (y)Answer y to that. You’ll see a bunch more questions, which we’ll go through individually:create-svelte version 2.1.0Welcome to SvelteKit!? Where should we create your project?  (leave blank to use current directory) ›Since you’re already in the birthdays directory, just leave this blank, and hit Enter. Next, you’ll be asked about which app template you’d like to use:? Which Svelte app template? › - Use arrow-keys. Return to submit.    SvelteKit demo app❯   Skeleton project - Barebones scaffolding for your new SvelteKit app    Library skeleton projectChoose Skeleton project. Next, you’ll be asked about TypeScript:? Add type checking with TypeScript? › - Use arrow-keys. Return to submit.    Yes, using JavaScript with JSDoc comments    Yes, using TypeScript syntax❯   NoFor this question, I’ve chosen No. That’s because this book is about testing techniques, not typing techniques. That’s not to say that this book doesn’t apply to TypeScript projects – it most certainly does – just that typing is not the topic at hand.

If you want to use TypeScript

If you’re a seasoned TypeScript developer, please feel free to choose that option instead. The code samples in the book won’t need too much modification except for the additional type definitions, which you’ll need to provide.

Finally, you’ll be asked about extra package dependencies:? Add ESLint for code linting? › No / Yes? Add Prettier for code formatting? › No / Yes? Add Playwright for browser testing? › No / Yes    ✔ Add Vitest for unit testing? … No / YesChoose Yes as the answer to all these questions. Although we won’t mention ESLint in this book, it’s always good to have. And we’ll need Playwright and Vitest.

You’ll then see a summary of all your choices, followed by a Next steps list:

Your project is ready!✔ ESLint  https://github.com/sveltejs/eslint-plugin-svelte3✔ Prettier  https://prettier.io/docs/en/options.html  https://github.com/sveltejs/prettier-plugin-svelte#options✔ Playwright  https://playwright.dev✔ Vitest  https://vitest.devInstall community-maintained integrations:  https://github.com/svelte-add/svelte-addersNext steps:  1: npm install (or pnpm install, etc)  2: git init && git add -A && git commit -m "Initial commit" (optional)  3: npm run dev -- --open

We’ll perform these next steps but before we do that, we’ll run some extra verification steps. It’s always good to check your work.

Type npm install into the Terminal and confirm that everything is installed correctly. Then, go ahead and commit your changes. (If you’ve forked the GitHub repository, you won’t need to use the git init command.)

Committing early and often

It’s a good idea to be checking in your work very often. While you’re learning the TDD approach to testing, it can be helpful to check in after every single test. This might seem like a lot but it will help you backtrack in case you get stuck.

Then, run npm run dev – –open. It should open your web browser and show you a "Welcome to SvelteKit" message.

You can then close the browser and hit Ctrl + C in the Terminal to stop the web server.

Next, let’s verify the Playwright and Vitest dependencies.

Installing and running Playwright

Although we won’t use Playwright in this chapter, it’s a good idea to get it installed and verify that it’s working.

Start by running npm test at the command line:

If you’ve never installed Playwright before, you’ll see a message like thepreceding one.

Playwright has its own environment setup to do, such as installing Chromium onto your machine. You can install it with the following command:

npx playwright install

Then, trying npm test again should give you the following output, showing that the one example test that’s included is passing:

> [email protected] test > playwright test Running 1 test using 1 worker [WebServer] [WebServer] [WebServer] Generated an empty chunk: "hooks". [WebServer]   ✓  1 test.js:3:1 › index page has expected h1 (307ms)   1 passed (4s)

This test, index page has expected h1, is a test for the "Welcome to SvelteKit" message you saw earlier when you launched the application in the browser.

Running Vitest

Running npm run test:unit is the default way to run Vitest tests. Try it now:

work/birthdays % npm run test:unit > [email protected] test:unit > vitest DEV  v0.25.8 /Users/daniel/work/birthdays ✓ src/index.test.js (1) Test Files  1 passed (1)       Tests  1 passed (1)    Start at  15:56:18    Duration  737ms (transform 321ms, setup 0ms, collect 16ms, tests 2ms) PASS  Waiting for file changes...        press h to show help, press q to quit

This automatically puts you in watch mode, which means any changes to the filesystem will cause tests to re-run. Press q to quit this mode. I personally don’t use watch mode and we won’t be using it in this book. See the Creating a shell alias section for a little discussion on why this is.

In the next section, we’ll make the ergonomics of the project a little easier for us.

Preparing your development environment for frequent unit testing

In this section, we’ll take some configuration actions that will make our test-driven lives much simpler.

Choosing your editor

Let’s start with your choice of code editor. More than likely, this means a choice between an IDE, such as Visual Studio Code, or a plain text editor, such as Vim or Emacs.

IDEs tend to have lots of bells and whistles and one of those is the built-in test runner, which runs tests for you and integrates test output into the editor itself. On the other hand, plain text editors will require you to have a separate Terminal window for you to enter test commands directly, as you did in the previous section.

Figure 1.1 shows how my own setup looks, using Vim and tmux to split windows. The top half of the screen is where I edit my source files, and when I’m ready to run tests, I can switch to the bottom half and enter the test command.

Figure 1.1 – Using tmux and Vim

Figure 1.2 shows the same project in Visual Studio Code with the Vitest extension installed. Notice the test runner has a bunch of neat features, such as the ability to filter the test output, and green ticks next to the line numbers of passing tests.

Figure 1.2 – Using Visual Studio Code to run tests

I think there is a lot to learn from using a plain editor and Terminal setup, but if you don’t feel comfortable with that, then it’s best to stick to your favorite IDE for now.

The one thing you want to make sure of is that it’s easy and quick to run tests. So, if you’re writing a new test, you want to immediately run it and see it fail. And if you’re making a test pass or refactoring tests, make sure you can quickly re-run tests to check your progress.

Creating a shell alias

If you’re choosing to use the Terminal to run tests, then you will almost certainly want to set up an alias to make it simpler to run Vitest unit tests. You’ll recall that there are two commands that you use for running tests: npm test for Playwright tests and the npm run test:unit command for Vitest unit tests.

The style of testing shown in this book follows the classic test pyramid approach to testing, which states that we should have lots of little unit tests (in Vitest) and far fewer system tests (in Playwright).

So, given that we’ll be working much more frequently with Vitest, doesn’t it make sense to have the shortertest command be the one that runs unit tests?

The solution that I use is a shell alias, v, that invokes Vitest. If you wanted to use the standard watch mode, you’d set up the shell alias to run this command:

npx vitest

However, because I don’t want to use watch mode, I set it up to use this command:

npx vitest run

I‘d suggest you use this version, at least while you read through this book. I find that watch mode tends to break silently, especially when you’re in the first stages of setting up a project. To avoid confusion, better to just invoke the test command when you’re ready.

On my Mac, my default shell is zsh