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
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
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">
<head>
<meta charset="utf-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="Stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlightjs@9.16.2/styles/github.css">
</head>
<body>
<h1>Title</h1>
Body
</body>
</html>`
);
});
Thoughts
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)