DEV Community

Cover image for How to Build and Test a Blog with Svelte and SvelteKit
Ben ltaif
Ben ltaif

Posted on • Updated on

How to Build and Test a Blog with Svelte and SvelteKit

If you're looking for a modern way to build a blog, Svelte and SvelteKit are great options. Svelte is a lightweight, reactive framework that compiles your code to highly optimized vanilla JavaScript. SvelteKit is a framework for building web applications that builds on top of Svelte, providing server-side rendering, routing, and other features.

In this tutorial, we'll show you how to build a simple blog with SvelteKit, and how to write unit tests for it using jest and svelte-jester. By the end of the tutorial, you'll have a fully functional blog that's ready to deploy, and you'll have the tools to test it and ensure its quality.

Building the Blog

Creating a new SvelteKit project
To get started, you'll need to create a new SvelteKit project. The easiest way to do this is to use degit, a tool for cloning repositories.

Open a terminal and run the following command:

npx degit sveltejs/sveltekit my-blog
Enter fullscreen mode Exit fullscreen mode

This will create a new directory called my-blog and clone the SvelteKit starter template into it.

Creating the basic pages and routes
Next, we'll create the basic pages and routes for the blog. In SvelteKit, pages are created as .svelte files in the src/routes directory.

Let's start by creating the home page. Create a new file called index.svelte in the src/routes directory, and add the following code:


<script>
  export let posts = [];
</script>

<h1>Welcome to my blog!</h1>

{#if posts.length}
  <ul>
    {#each posts as post}
      <li>
        <a href={`blog/${post.id}`}>
          {post.title}
        </a>
      </li>
    {/each}
  </ul>
{:else}
  <p>No posts yet.</p>
{/if}
Enter fullscreen mode Exit fullscreen mode

This code defines a Svelte component that displays a list of blog posts. The export let posts line defines a property that can be passed to the component from a parent component or from the route definition.

Next, let's create a route definition for the home page. Create a new file called index.json.js in the src/routes directory, and add the following code:

import posts from './_posts.js';

export async function get() {
  return {
    body: {
      posts
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

This code defines a route that returns a JSON object containing the list of blog posts. The posts array is imported from a file called _posts.js, which we'll create next.

Let's create the _posts.js file now. Create a new file called _posts.js in the src/routes directory, and add the following code:


export default [
  {
    id: '1',
    title: 'My First Blog Post',
    content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
  },
  {
    id: '2',
    title: 'My Second Blog Post',
    content: 'Vivamus euismod metus sit amet arcu consectetur, vel ultricies dolor fringilla.'
  }
];
Enter fullscreen mode Exit fullscreen mode

This code defines an array of two blog post objects. Each object has an id, a title, and a content property.

Now we have a basic home page that displays a list of blog posts. Let's create some more pages for the blog

Creating individual blog post pages

Next, we'll create individual pages for each blog post. Create a new file called [_id].svelte in the src/routes directory, and add the following code:

<script>
  export let post = {};
</script>

<h1>{post.title}</h1>

<p>{post.content}</p>
Enter fullscreen mode Exit fullscreen mode

This code defines a Svelte component that displays a single blog post. The export let post line defines a property that can be passed to the component from a parent component or from the route definition.

Next, let's create a route definition for the individual blog post pages. Create a new file called [_id].json.js in the src/routes directory, and add the following code:

import posts from './_posts.js';

export async function get({ params }) {
  const post = posts.find(p => p.id === params.id);
  if (post) {
    return {
      body: {
        post
      }
    };
  } else {
    return {
      status: 404
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

This code defines a dynamic route that takes an id parameter from the URL. It then searches for a blog post object with that id in the posts array, and returns it as a JSON object. If the id doesn't match any blog post, it returns a 404 status.

Styling the blog
Now that we have the basic pages and routes set up, let's add some styles to the blog. SvelteKit comes with support for CSS modules out of the box, so we'll use that to style our components.

Create a new file called global.css in the src directory, and add the following code:


h1 {
  font-size: 2.5rem;
  margin: 2rem 0;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  margin: 1rem 0;
}

a {
  color: #000;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
Enter fullscreen mode Exit fullscreen mode

This code defines some basic styles for the blog, such as font sizes, margins, and text decoration.

Next, we'll import this CSS file into our Svelte components. In each .svelte file, add the following line at the top:

<style global>
  @import './global.css';
</style>
Enter fullscreen mode Exit fullscreen mode

This code imports the global.css file into the component's styles.

Building and testing the blog

Now that we have our blog built, let's build and test it. To build the blog, run the following command in the terminal:

npm run build
Enter fullscreen mode Exit fullscreen mode

This will compile the Svelte code and create a production-ready build in the build directory.

To test the blog, we'll use jest and svelte-jester. jest is a popular JavaScript testing framework, and svelte-jester is a plugin that allows us to write unit tests for Svelte components.

First, let's install the dependencies. Run the following command in the terminal:

npm install --save-dev jest svelte-jester
Enter fullscreen mode Exit fullscreen mode

Next, create a new file called example.test.js in the src directory, and add the following code:

import { render } from '@testing-library/svelte';
import Example from './Example.svelte';

test('renders the text "Hello, world!"', () => {
  const { getByText } = render(Example);
  expect(getByText('Hello, world!')).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

This code defines a unit test for a Svelte component called Example. It uses the render function from @testing-library/svelte to render the component, and the getByText function to find an element with the text "Hello, world!". The expect function checks that the element is in the document.

You can run the tests by running the following command in the terminal:

npm run test
Enter fullscreen mode Exit fullscreen mode

This will run all the tests in the src directory.

In this tutorial, we've seen how to build a blog using Svelte and SvelteKit. We've created a home page that displays a list of blog posts, individual pages for each blog post, and added some basic styles to the blog. We've also learned how to test our Svelte components using jest and svelte-jester.

Svelte and SvelteKit offer a powerful and simple way to build web applications, and their small size and performance make them ideal for modern web development.

Top comments (0)