Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write unit test for loading handlebars template file in Jest?

In my reactjs project, I am using handlebars to generate source code from the template. These templates are saved in files. In order to load these files into javascript, I configured below configuration in webpack:

{
        test: /\.handlebars|hbs$/,
        loader:
          'handlebars-loader?helperDirs[]=' +
            path.join(__dirname, '../src/helpers/handlebars')
      },

it works fine when I launch the production. But it doesn't work in my unit tests. I am using jest as unit test framework. I have seen some people suggest to use Handlebars.registerHelper. I know it works only for the template from string. How to solve the issue when I load the template from files?

like image 764
Joey Yi Zhao Avatar asked Jul 25 '17 10:07

Joey Yi Zhao


People also ask

How do I compile handlebars templates?

Getting started Next, install the Handlebars npm package, which contains the precompiler. Create a file name example. handlebars containing your template: Handlebars <b>{{doesWhat}}</b> precompiled!

Is handlebars a template engine?

Handlebars: What it is and Why to Use itHandlebars is a logic-less templating engine that dynamically generates your HTML page.


2 Answers

I created a preprocessor that simply put the handlebars template into a module so when imported in javascript via an 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 a src file...

import Mn from 'backbone.marionette';
import template from './template.hbs';

const ToggleList = Mn.CompositeView.extend({
  template,
});

export default ToggleList;
like image 127
Drawman Avatar answered Sep 24 '22 23:09

Drawman


When loading handlebar 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 please add the following rule to the transform object in your jest configuration:

"jest": {
    // ...
    transform: {
        "\\.hbs$": "jest-handlebars",
    }
    // ...
}

Now all imported handlebars files will get compiled by the processor and the render function is imported.

like image 41
user3623641 Avatar answered Sep 24 '22 23:09

user3623641