Testing Vanilla JavaScript ES Modules With Deno

January, 2023

TL;DR

I setup Deno to test ES modules written in vanilla JavaScript. I tried Jest and Vitest first. They didn't work.

Sample code demonstrating the methodology in The Code section below.

Overview

I'm learning Rust with The Rust Book, Rust By Example and Rust Adventure. Doing write-ups of what I'm learning is part of my process. I'm going full bore with that by making an entire site dedicated to Rust.

The site is built with mdbook (which is amazing) and some vanilla JavaScript written in ES Modules. Figuring out how to test the modules was a pain. I spent a hours trying to get Jest and Vitest to work. Using them without turning everything into a npm project was beyond me.

I'm not opposed to npm projects, but having to set one up solely for testing felt gross. Chris Biscardi (who runs Rust Adventure) turned me on to Deno. It has a built-in testing feature that does exactly what I need.

Once you have Deno installed, the test process is delightfully straight forward. Two files are all you need: The one you're testing and the one you're testing with.

The Code

Here's the test file followed by the file to test:

example_test.js


import { assertEquals } from 'https://deno.land/std@0.173.0/testing/asserts.ts'
import { example } from './example.js'

Deno.test('example test', () => {
  assertEquals(example(), true)
})

example.js


export const example = () => {
  return true
}

That's it. As long as the test file ends with _test.js you're good to go.

Running The Tests

Testing is done by running this command in the same directory as the files:

deno test

The output will look like this:

running 1 test from ./example_test.js
example test ... ok (6ms)

ok | 1 passed | 0 failed (19ms)

Given how much time I spent with the other tools it was super nice to have Deno actually just work out of the box.

Outro

I was surprised how hard it was to figure this out. Especially since the solution didn't come from searching the web. It came from a direct recommendation.

My search-fu may have been off, but it's hard not to feel like I'm alone out here when I want to do things without npm. The Deno solution proves that's not the case. But, it does make me wonder: How many folks aren't using more vanilla approaches simply because of the lack of information?