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

Viewed 4083

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?

2 Answers

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.

Related