How do I write a unit test to load a descriptor template file in Jest?
In my reactjs project I am using handlebars to generate source code from template. These templates are saved in files. To load these files in javascript, I configured the below config in webpack
:
{
test: /\.handlebars|hbs$/,
loader:
'handlebars-loader?helperDirs[]=' +
path.join(__dirname, '../src/helpers/handlebars')
},
it works fine when i start production. But that doesn't work in my unit tests. I am using jest
as a unit test framework. I've seen some people suggest using Handlebars.registerHelper
. I know it only works for template from string
. How to solve the problem when loading a template from files?
source to share
I created a preprocessor that just put the handlebars template in a module, so when importing to javascript via es6 import it can be used.
// preprocessor.js
module.exports = {
process(src) {
return `
const Handlebars = require('handlebars');
module.exports = \`${src}\`;
`;
},
};
Then in my package .json ...
// package.json
"jest": {
"collectCoverage": true,
"modulePaths": [
"./app",
"./node_modules"
],
"testPathIgnorePatterns": [
"/node_modules/",
"/app/bower_components/"
],
"moduleFileExtensions": [
"js",
"hbs"
],
"transform": {
"\\.js$": "babel-jest",
"\\.hbs$": "<rootDir>/app/scripts/preprocessor.js"
}
}
In the src file ...
import Mn from 'backbone.marionette';
import template from './template.hbs';
const ToggleList = Mn.CompositeView.extend({
template,
});
export default ToggleList;
source to share
When loading handlebars templates while testing with Jest, I found that the jest-handlebars package solved my problem.
From the docs:
npm i jest-handlebars --save-dev
To enable the processor, add the following rule to the transform object in the jest setup:
"jest": { // ... transform: { "\\.hbs$": "jest-handlebars", } // ... }
Now all imported descriptor files will be compiled by the processor and the render function will be imported.
source to share