3

Svelte with TypeScript and Jest (Starter Project)

 2 years ago
source link: https://daveceddia.com/svelte-typescript-jest/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In the summer of 2020, Svelte added TypeScript support. Turning it on is as simple as running a single script! But the default starter project doesn’t have Jest testing set up.

I took the default Svelte starter with TypeScript and added Jest to it, along with a couple sample tests. The final project is here.

This was pieced together from info at the Svelte testing library docs, the Svelte Society repo’s testing recipes section, and the README for svelte-jester.

DIY or Use My Starter

If you want to apply the steps to an existing project of yours, or just to learn how it works, feel free to follow the steps below.

Or if you’re starting a fresh project and you just want to get going, you can clone my starter project that has all of this set up already:

npx degit 'dceddia/svelte-typescript-jest#main' your-svelte-project
cd your-svelte-project
npm install
npm test

(Don’t forget the quotes around the repo + branch name if you’re using Zsh)

You should see 2 passing tests, and be all ready to go!

Read on for the changes I made to get it working.

1. Clone the standard Svelte starter

The defacto standard way to start a new Svelte project is to use the degit tool to clone the repo while removing extra Git folders:

$ npx degit sveltejs/template svelte-typescript-jest

2. Setup Svelte + TypeScript

The official starter project can work in two modes: plain JavaScript (the default) or TypeScript.

To convert it to TypeScript, we can run the provided setupTypeScript.js to modify a few files and set up the build.

Switch into the project directory and run the script, then install all the packages.

cd svelte-typescript-jest
node scripts/setupTypeScript.js
npm install

3. Add Jest support, Testing Library, and svelte-jester

Here we’re installing a bunch of stuff:

  • jest to run the tests
  • ts-jest to let you write your tests in TypeScript
  • @testing-library/svelte for some useful functions to test your Svelte components with
  • @testing-library/jest-dom for handy DOM matcher functions like toBeInTheDocument
  • svelte-jester to compile Svelte components for Jest, so that Jest can use them
  • @types/jest to get TS to stop complaining about Jest’s globals like expect
  • babel-jestoptional – to let you write your tests in JavaScript
  • @babel/preset-env to go with babel-jest, also optional
npm install --save-dev \
    jest ts-jest \
    @testing-library/svelte @testing-library/jest-dom \
    svelte-jester @types/jest \
    babel-jest @babel/preset-env

4. Add test script to package.json

With this addition, you’ll be able to run npm test to run the tests, or npm run test:watch to run them & watch for changes.

package.json
{
  "scripts": {
    ...
    "test": "jest",
    "test:watch": "npm test -- --watch"
  }
}

5. Add the Jest config to package.json

We need to configure Jest to tell it what to do with .svelte, .ts, and .js files. If you only want to write test in TypeScript, you can skip the .js config.

This needs to be a top-level key in package.json, at the same level as “scripts” and “dependencies” and the others.

package.json
{
  "scripts": { ... },
  ...
  "jest": {
    "transform": {
      "^.+\\.svelte$": [
        "svelte-jester",
        {
          "preprocess": true
        }
      ],
      "^.+\\.ts$": "ts-jest",
      "^.+\\.js$": "babel-jest"
    },
    "moduleFileExtensions": [
      "js",
      "ts",
      "svelte"
    ]
  }
}

6. Create svelte.config.js

Make a new file at the root of the project named svelte.config.js and paste in this code.

svelte.config.js
const sveltePreprocess = require("svelte-preprocess");

module.exports = {
  preprocess: sveltePreprocess(),
};

The svelte-preprocess package comes by default with the Svelte starter project that we cloned, so we don’t need to install it.

I noticed that everything worked fine without this file until I added support for JS tests with Babel. So if you’re writing your tests in TS and skipping the Babel stuff, you might not need this.

7. Add jest to tsconfig.json

Open your tsconfig.json file, which should already exist since running the setupTypeScript.js script, and add this compilerOptions section.

tsconfig.json
{
  ...
  "compilerOptions": {
    "types": ["jest"]
  }
}

8. Create tests under src/__tests__

To verify that everything is working, create a src/__tests__/hello.test.ts file and paste this in:

Jest will look for tests under the src/__tests__ directory.

import { render } from "@testing-library/svelte";
import App from "../App.svelte";

test("should render", () => {
  const results = render(App, { props: { name: "world" } });

  expect(() => results.getByText("Hello world!")).not.toThrow();
});

Here we’re using the render function from testing-library to, well, render our Svelte component with some props. Then we check the rendered results to make sure the props we passed in did in face appear on the page.

9. Try it out!

All that’s left is to make sure everything worked. Run the tests, and you should see it pass:

npm test

Want to get better at React?

I send an article every Wednesday to help you level up as a front-end React developer. Drop your email in the box if you'd like to get on the list.

Email Address
I respect your email privacy. Unsubscribe any time.

Learning React can be a struggle — so many libraries and tools!
My advice? Ignore all of them :)
For a step-by-step approach, check out my Pure React workshop.

Pure React plant

Learn to think in React

  • 90+ screencast lessons
  • Full transcripts and closed captions
  • All the code from the lessons
  • Developer interviews
Start learning Pure React now

Dave Ceddia’s Pure React is a work of enormous clarity and depth. Hats off. I'm a React trainer in London and would thoroughly recommend this to all front end devs wanting to upskill or consolidate.

Alan Lavender
Alan Lavender
@lavenderlens
Login
photo?commenterHex=1edba355014f01d1009559edbd2cd19692bbeb0e19b81bb374985c2d79f6bcdeNoel da Costa
1 point
9 months ago

All good except the last step. ReferenceError: document is not defined

photo?commenterHex=29d1b94f0817a3c6a65b8f3ec0cf71bef9d0bab9d8ee6e9507a713c7d0616f42JBef
0 points
7 months ago

same for me

Balla Dom
0 points
11 months ago

Worked on first try :) Thanks!

photo?commenterHex=70603e7c46fd6d14f2048c04c7a2555fe14e388186fb8fa91fd7833b8efed4f8Simon Hampton
0 points
6 months ago

I'm seeing errors like

``` /Users/simonhampton/code/svelte/de-kam/node_modules/svelte-material-icons/GlassMug.svelte:1 ({"Object.":function(module,exports,require,dirname,filename,jest){ ^

SyntaxError: Unexpected token '<'

  1 | import type { BaseData } from "./types";
  2 |
> 3 | import GlassMug from "svelte-material-icons/GlassMug.svelte";
    | ^
  4 | import GlassWine from "svelte-material-icons/GlassWine.svelte";
  5 | import Beer from "svelte-material-icons/Beer.svelte";
  6 | import Coffee from "svelte-material-icons/Coffee.svelte";

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK