How To Configure Jest 28+ To Work With HTML Imports

Jest
How To Configure Jest 28+ To Work With HTML Imports

If you have an application that has HTML imports like this import template from './my-component.html and then attempt to test this code in Jest 28+ (or previous versions, for that matter), you will get a syntax error similar to this one:

SyntaxError: Unexpected token ‘<’ HTML

Fortunately, there is an easy fix. Firstly, you need to install the package jest-html-loader. npm install jest-html-loader -D. Then you need to configure your Jest configuration as follows.

"transform": {
    "^.+\\\\.tsx?$": "ts-jest",
    "^.+\\\\.html?$": "jest-html-loader"
  },

That is all you need to do. Your HTML imports will work and not throw errors during your test process.

How To Mock uuid In Jest

When it comes to mocking dependencies in Jest, it couldn’t be easier. You can create an actual mock module that gets loaded in place of the …

How To Easily Mock Moment.js In Jest

Recently whilst writing some unit tests in Jest, I had to test some code that took ISO date strings and converted them to formatted date strings, then …