I'm trying to create a directive that has behaviour similar to v-if
. Basically if the condition is true, the element should exist, if it's false, it shouldn't. I also need to ensure that those changes pass JEST tests. The purpose is to create a permissions plugin (so I don't need to use v-if="$isAllowed('edit', 'comments')"
syntax)
I've looked at this and this tickets. The directive works, as in it replaces the element with a comment in the rendered DOM, however when running tests, the element still exists.
the directive:
Vue.directive('allow', (el, binding, vnode) => {
if (!isAllowed(binding.value)) {
const comment = document.createComment(' ');
Object.defineProperty(comment, 'setAttribute', {
value: () => undefined,
});
vnode.elm = comment;
vnode.text = ' ';
vnode.isComment = true;
vnode.context = undefined;
vnode.tag = undefined;
vnode.data.directives = undefined;
if (vnode.componentInstance) {
vnode.componentInstance.$el = comment;
}
if (el.parentNode) {
el.parentNode.replaceChild(comment, el);
}
}
});
Template:
...
<div v-allow="['edit', 'comments']" test-name="comment">
<!-- some irrelevant code here -->
</div>
...
The test:
it('does not render element when user has no access to it', () => {
expect(wrapper.find('[test-name="comment"]').exists()).toBeFalsy();
});
The test fails (saying component exists). However, when I print the rendered html (console.log(wrapper.html());
), it prints comment instead of the component.