This week's task is to add tests to my program. I used Jest as my testing tool as it is well-developed and very popular among Javascript users.
Setting up Jest
I ran an npm
command to install Jest
and added it to devDependencies
npm install --save-dev jest
I then added a script to scripts
in package.json
in order to run jest
.
"scripts": {
"test": "jest --"
},
Testing the program
I started testing my index.js
file which is responsible for parsing command line arguments. I had to edit a few pieces of code to make testing easier. Below is an example
describe("Testing parseCommand()", () => {
reset();
test("Input file path not specified", () => {
const error =
"error: required option '-i, --input <file path>' not specified";
const option = {};
const boolean = parseCommand(option);
expect(finalize(logOutput)).toBe(null);
expect(finalize(errorOutput)).toEqual(error);
expect(boolean).toBe(0);
});
The challenging part was ssg.js
file because I had conflicts between fs
and fs.promise
and the way it was written, it was quite hard to test some functions using custom mock
. I had to edit some code so that I could test one of the functions. Below is one of the tests.
describe("Testing createHTMLFile() with '.md' file", () => {
const filename = "file.md";
const ext = ".md";
const fileData = `# Javascript Static Site Generator (SSG)
A Javascript command line program that converts **.txt** and **.md** files into **.html** files.`;
beforeAll(() => {
fs.__setMockFileData(`${filename}`, fileData);
});
test("'.md' file", async () => {
ssg = new SSG(null, null, null);
const res = await ssg.createHTMLFile(filename, ext);
expect(ssg.toBeGenerated_.length).toEqual(1);
expect(ssg.toBeGenerated_[0].html).toEqual('<!DOCTYPE html>\n <html lang="en-CA">\n <head>\n <meta charset="utf-8" />\n <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />\n <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css" />\n <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.3.1/styles/default.min.css">\n <title>Javascript Static Site Generator (SSG)</title>\n </head>\n <body>\n <main>\n <div class="mainContent">\n <h1>Javascript Static Site Generator (SSG)</h1>\n<p>A Javascript command line program that converts <strong>.txt</strong> and <strong>.md</strong> files into <strong>.html</strong> files.</p>\n\n </div>\n </main>\n </body>\n </html>');
});
});
Through testing, I realized that it's important to break my code into small pieces and to modularize them, I will refactor my code again and add more tests. This week has been quite hectic π
Top comments (0)