Testing Vanilla JavaScript ES Modules With Deno
#TL;DR
I setup https://deno.land/][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 https://doc.rust-lang.org/book/][The Rust Book, https://doc.rust-lang.org/rust-by-example/][Rust By Example and https://www.rustadventure.dev/][Rust Adventure. Doing write-ups of what I'm learning is part of my process. I'm going full bore with that by making https://typing-rust.alanwsmith.com/][an entire site dedicated to Rust.
The site is built with https://rust-lang.github.io/mdBook/][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. https://www.youtube.com/@chrisbiscardi][Chris Biscardi (who runs https://www.rustadventure.dev/][Rust Adventure) turned me on to https://deno.land/][Deno. It has a https://deno.land/manual@v1.29.4/basics/testing][built-in testing feature that does exactly what I need.
Once you have Deno https://deno.land/manual@v1.29.4/getting_started/installation][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
Deno.# example.js
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 testThe 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?
# Bonus Points
Here's an HTML file that uses the .js file:
#+begin_export html
#+end_export