How - To Use Jest To Test Vanilla JavaScript Files Without A Framework
## The Issue
I'm building a plain old html and vanilla javascript site. I decided I wanted to setup a test suite and picked Jest since it was the first search result. The Jest page says "It works with projects using : Babel, TypeScript, Node, React, Angular, Vue, and more!" It took a little hunting to figure out how to run it without using any of those frameworks. Here's what I ended up with. It provides [TODO: Code shorthand span ] on the command line for vanilla javascript testing.
## The Process
1. Install jest globally
2. Create a jest.config.js file in your working directory with :
const config =
module.exports = config
3. Create a [TODO: Code shorthand span ] directory in your working directory
4. Create a test file in your [TODO: Code shorthand span ] directory (e.g. ` tests/functions.test.js ` )
const functions =
4. Create the file to be tested in your working directory (e.g. ` functions.js ` )
5. Run jest from the command line with :
When you fire that off, you'll get the output from jest that looks something like this :
The process stays open and runs tests as you make changes. Press [TODO: Code shorthand span ] to exit it.
- You only need to do the first step (where you install jest globally) once
- The [TODO: Code shorthand span ] command hangs if you try to run it without a configuration (e.g. ` jest.config.js ` ) file
- Jest uses a Node environment by default. The [TODO: Code shorthand span ] line in the [TODO: Code shorthand span ] file switches to JSDOM which allows you to use things like ` document.addEventListener('DOMContentLoaded', function () {} `
- More details on the configuration options are here
- The [TODO: Code shorthand span ] check is to prevent a [TODO: Code shorthand span ] error when the file is used in the browser
- Use [TODO: Code shorthand span ] instead of [TODO: Code shorthand span ] to do a single run instead of watching files
- If you're in a git repo, you can also do [TODO: Code shorthand span ] instead of [TODO: Code shorthand span ] to focus on files that are in the repo
- The examples on the jest site only export one function per file. With the code above, you can test multiple functions in a single file (e.g. you could add a function called [TODO: Code shorthand span ] , export it with [TODO: Code shorthand span ] , and test it with [TODO: Code shorthand span ]