Snowpack - Running Tests with @web/test-runner

10/03/2021, Sun
Categories: #shell #JavaScript
Tags: #NodeJs

Set up @web/test-runner

Snowpack recommends that @web/test-runner be used as the test runner of choice. Using this setup will allow you to conveniently run tests that would run in the browser after the Snowpack dev server has started.

First, install the dependencies found in the "devDependencies" in package.json with

npm install @esm-bundle/chai @snowpack/web-test-runner-plugin @web/test-runner

In the package.json, add in the "web-test-runner \"src/tests/*.test.js\" --node-resolve" for the test key for calling upon the test runner.

{
    "name": "Project",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "author": "",
    "license": "ISC",
    "dependencies": {
        "snowpack": "^3.8.8"
    },
    "scripts": {
        "start": "snowpack dev",
        "test": "web-test-runner \"src/tests/*.test.js\" --node-resolve"
    },
    "devDependencies": {
        "@esm-bundle/chai": "^4.3.4-fix.0",
        "@snowpack/web-test-runner-plugin": "^0.2.2",
        "@web/test-runner": "^0.13.18"
    }
}

Create the 'web-test-runner.config.js' file, and reference the 'web-test-runner-plugin':

// web-test-runner.config.js

process.env.NODE_ENV = 'test';

module.exports = {
  plugins: [require('@snowpack/web-test-runner-plugin')()],
};

Snowpack also requires a mount source and an output url in the snowpack.config.js for the tests to run properly.

// snowpack.config.js

module.exports = {
  mount: {

    // 'the-source-folder-name': { url: 'the-serving-path-in-the-browser'}
    src: { url: '/dist' }
  }
};

Create a simple test case in the "src/test" folder for testing:

// sample.test.js

import { expect } from '@esm-bundle/chai';

it('sum of 1 plus 1 equals 2', () => {
    expect(1 + 1).to.equal(2);
});

Finally, run the test command:

npm run test