Book Image

Svelte with Test-Driven Development

By : Daniel Irvine
Book Image

Svelte with Test-Driven Development

By: Daniel Irvine

Overview of this book

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.
Table of Contents (22 chapters)
1
Part 1: Learning the TDD Cycle
8
Part 2: Refactoring Tests and Application Code
16
Part 3: Testing SvelteKit Features

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:

  1. 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 birthdays
    cd birthdays
    npm 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]
Ok to proceed? (y)
  1. Answer y to that. You’ll see a bunch more questions, which we’ll go through individually:
    create-svelte version 2.1.0
    Welcome to SvelteKit!
    ? Where should we create your project?
      (leave blank to use current directory) ›
  2. 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 project
  3. Choose 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
       No
  4. For 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.

  1. 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 / Yes
  2. Choose 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.dev
Install community-maintained integrations:
  https://github.com/svelte-add/svelte-adders
Next 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:

work/birthdays % npm test
> [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 (7ms)
  1) test.js:3:1 › index page has expected h1 =============================================
    browserType.launch: Executable doesn't exist at /Users/daniel/Library/Caches/ms-playwright/chromium-1041/chrome-mac/Chromium.app/Contents/MacOS/Chromium
    ...
  1 failed
    test.js:3:1 › index page has expected h1 ============================================

If you’ve never installed Playwright before, you’ll see a message like the preceding 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.