DEV Community

Cover image for How to Unit Test HTML and Vanilla JavaScript Without a UI Framework

How to Unit Test HTML and Vanilla JavaScript Without a UI Framework

Tyler Hawkins on April 23, 2020

Recently I was curious about something: Is it possible to write unit tests for front end code that doesn’t use any sort of UI framework or develope...
Collapse
 
jwp profile image
JWP • Edited

Over the top good news. I find Karma to be untenable most of the time, I want to avoid it, and have written a number of articles to that extent. None of them giving me a total solution. I will try your recommendations as I think, this method would also work for Angular which is my arena.... Thanks Tyler!!!!!!

Collapse
 
thawkin3 profile image
Tyler Hawkins

You're welcome! Let me know if you discover anything interesting in your testing!

Collapse
 
tylerlwsmith profile image
Tyler Smith

Legendary. I've been coding a lot of Vanilla JS lately, and imperative DOM manipulation feels very fragile compared to React. I'm going to use the techniques here to start adding some tests to make sure I don't break anything.

Collapse
 
tromgy profile image
Tromgy

Excellent! Helped me a lot. I was facing exactly the same task. I was aware of the runScripts: 'dangerously' option, but I tried to configure it from jest.config.js without any luck.

Collapse
 
destroyer22719 profile image
Nathan Cai

Hi there! It's a great article and all, but how do I test individual functions, variables, etc. in an external JavaScript file?

Collapse
 
saifahn profile image
sean

That should be simple enough to do just using Jest (or any other testing framework). Export the functions etc. from the Javascript file, import them into a test file and use your testing framework to assess that the functions work correctly. :)

Unless I have misunderstood the question...

Collapse
 
destroyer22719 profile image
Nathan Cai

Hi there! There are issues with ESM and what if these JS functions have DOM manipulations? Those seem to be my issues.

Collapse
 
amin05th profile image
Amin05th

I have a question i tried to move the script to a new file and an the test doesn' t work anymore. What can I do?