DEV Community

Minh Hang Nguyen
Minh Hang Nguyen

Posted on

Add testing to SSG

For this lab, I picked Jest as the testing tool for mh-ssg. This is a popular Javascript testing framework thanks to its simplicity and ease of usage.

The framework can be easily installed with the following command

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

Since mh-ssg is using ESLint, I also have to install eslint-plugin-jest so that ESLint can work with Jest.

yarn add --dev eslint eslint-plugin-jest
Enter fullscreen mode Exit fullscreen mode

In .eslintrc config file, I added the plugin for Jest and "jest/globals": true to the env variable.

{
   "plugins": ["jest"],
   "env": {
      "jest/globals": true
   },
}
Enter fullscreen mode Exit fullscreen mode

I also configured the rules under the rules section

{
  "rules": {
    "jest/no-disabled-tests": "warn",
    "jest/no-focused-tests": "error",
    "jest/no-identical-title": "error",
    "jest/prefer-to-have-length": "warn",
    "jest/valid-expect": "error"
  }
}
Enter fullscreen mode Exit fullscreen mode

In this lab, I wrote some test cases for generateHTML.js and validateOutputFolder.js as unit tests. I realized that sometimes the code for testing can be even more than the code itself. Since the program might have several paths and in each path, it could direct even more sub-paths. Effective testing should cover most of these paths, hence, the amount of testing can be too much if we don't know which feature to focus on. For these test cases, I also learned about mocking. To be specific, I created a mock for the fs module to test the output folder.

Another thing I learned was to create end-to-end testing. In order to run this, I had to install another module - execa.

npm install execa
Enter fullscreen mode Exit fullscreen mode

I created run.js to execute the program for end-to-end testing.

const execa = require("execa");

async function run(...args) {
  try {
    const result = await execa.node("bin/index.js", args);
    return result;
  } catch (err) {
    return err;
  }
}
Enter fullscreen mode Exit fullscreen mode

Thinking from a testing perspective, there are a lot of scenarios to be tested since the program allows several options. I was planning to write tests for all scenarios but due to the limited time, I couldn't complete all of them. Currently, only the tests for --input are finished and other tests are commented out and I'll find some time to update them soon.

Top comments (0)