DEV Community

Francesco Menghi
Francesco Menghi

Posted on • Updated on

Code testing with Jest

This week I looked at code testing for my Static Site Generator static-dodo. I picked Jest for this since it is a very popular unit testing tool used by many open source projects.

How to setup Jest

I started by installing Jest using npm

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

then I added "test": "jest" to the "scripts" section of my package.json to be able to run tests with the simple command:

npm test
Enter fullscreen mode Exit fullscreen mode

Before getting into writing tests, I had to tackle a problem that I have been putting to the side: having a long code all in one file. I spent a lot of time refactoring to move some logic into different files and export those as modules.

Here is an example of a test I wrote to make sure that the correct html is returned by the writeHTML function:

test("writeHTML with Title, Body and Stylesheet should return correct html", () => {
  expect(writeHTML("Title", "Body", "Stylesheet")).toBe(
    `<!doctype html>
  <html lang="en">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="Stylesheet">
    <link rel="stylesheet" href="">
Enter fullscreen mode Exit fullscreen mode


I only scratched the surface of unit testing but I do find the process of writing tests pretty complicated, especially when it comes to creating Mock functions. I will need to get more familiar with Jest in the future and I have a lot more tests to add to the project.

Top comments (0)