ralfting
ralfting

Reputation: 213

Test not work without parentheses in VUEJS 2

I make testing to VueJS 2 application using Jest.

I need to test if a method was called when clicking in my button, the problem is, when I put my method in click without paratheses, he is not called in my test.

ButtonAnchor.vue

<template>
 <div>
  <a v-on:click="triggerAnchor">{{ text }}</a>
 </div>
</template>

<script>
  [...]
  methods: {
   triggerAnchor(event) { ... }
  },
</script>

BaseAnchor.spec.js

import { mount } from 'vue-test-utils';
import BaseAnchor from '@/components/BaseAnchor';

[...]

it('should called `triggerAnchor` when clicked button', () => {
  const vm = mount(BaseAnchor).vm;
  const buttonLink = vm.$el.querySelector('a');
  const spy = jest.spyOn(vm, 'triggerAnchor');

  buttonLink.click();
  expect(spy).toHaveBeenCalled();
});

Result jest test

● BaseAnchor › triggerAnchor › should called triggerAnchor when clicked button

expect(jest.fn()).toHaveBeenCalled()

Expected mock function to have been called.

If I put this way:

<template>
  <div>
    <a v-on:click="triggerAnchor()">{{ text }}</a> // Add parentheses
  </div>
</template>

It works, but I lost my event argument so my event.preventDefault() is undefined.

Upvotes: 0

Views: 420

Answers (1)

Jose Garrido
Jose Garrido

Reputation: 732

In Vue you can use event modifiers for v-on to implement e.preventDefault():

<a v-on:click.stop.prevent="triggerAnchor()">{{ text }}</a>

Upvotes: 1

Related Questions