mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 635 forks source link

Is there a way to override a macro with a mock? #1399

Closed kruncher closed 2 years ago

kruncher commented 2 years ago

For the purposes of testing it would be convenient to test if a template calls a macro with a specific set of parameters.

Is there a way to register some sort of macro override in JS which can capture the parameters of the macro call?

For example, the template might be:

{% if params.showFoo %}}
  {{ foo({ a: 42 }) }}
{% endif %}

And then in the unit test:

let fooParams;
nunjucks.mockMacro('foo', (params) => fooParams = params);

nunjucks.renderString(..., { showFoo: true });

expect(fooParams.a).toBe(42);
ogonkov commented 2 years ago

I'm not checked yet, but i guess you could use some kind of test nunjucks loader for templates. That mean that macro should be in separated files, i think it should do the trick.

https://mozilla.github.io/nunjucks/api.html#writing-a-loader

kruncher commented 2 years ago

@ogonkov that worked out pretty well thank you!