Ways to verify if a component triggers an event in VueJS

I am currently working with two components within my application. The Child component emits an 'input' event whenever its value is changed, and the Parent component utilizes v-model to receive this updated value. In order to ensure that the functionality is working correctly, I need to write a test using Vue-test-utils for the ChildComponent.

ParentComponent.vue:

<template>
 <div>
  <child-component v-model="search"></child-component>
  <other-component></other-component>
  ...
 </div>
</template>

ChildComponent.vue:

<template>
  <input :value="value" @change="notifyChange($event.target.value)"></input>
</template>

<script lang="ts">
  import { Component, Prop, Vue } from 'vue-property-decorator'

  @Component
  export default class ChildComponent extends Vue {

    @Prop({ default: '' }) readonly value!: string

    notifyChange(value: string) {
      this.$emit('input', value)
    }

  }
</script>

child-component.spec.ts:

describe('ChildComponent', () => {
   let wrapper: any
   before(() => {
   wrapper = VueTestUtils.shallowMount(ChildComponent, {})
  })

   it(`Should emit 'input' event when value changes`, () => {
    const rootWrapper = VueTestUtils.shallowMount(ParentComponent)
    wrapper.vm.value = 'Value'
    wrapper.findAll('input').at(0).trigger('change')
    assert.isTrue(!!rootWrapper.vm.search)
  })
})

Although not identical, the concept of my code resembles this structure. The components are functioning as expected, but there seems to be an issue with 'child-component.spec.ts'. I am in the process of writing a new test for this particular component.

Answer №1

TESTED. Here is a straightforward method to test an emit if anyone is seeking it out. Include this in your test describe.

describe('Close Button function', () => {
  it('emits false when the button is clicked', (done) => {
    wrapper.find('button').trigger('click')
    wrapper.vm.$nextTick(() => {
      wrapper.vm.closeModal() //closeModal is the method
      expect(wrapper.emitted().input[0]).toEqual([false]) //test for change
      done()
    })
  })
})

my vue component

<div v-if="closeButton == true">
      <button
        @click="closeModal()"
      >
      ...
      </button>
</div>

my props in vue components

 props: {
    value: {
      type: Boolean,
      default: false
    },

my methods in vue component

methods: {
    closeModal() {
      this.$emit('input', !this.value)
    }
  }

Answer №2

const componentWrapper = mount(Component)

componentWrapper.vm.$emit('bar')
componentWrapper.vm.$emit('bar', 456)

await componentWrapper.vm.$nextTick() // Make sure all $emits are processed

expect(componentWrapper.emitted('bar')).toBeTruthy()

Source:

Answer №3

To capture the emitted event "input" in your parent component, you need to listen for it.

<template>
 <div>
  <child-component @input="captureInputEvent" v-model="search"></child-component>
  <other-component></other-component>
  ...
 </div>
</template>

In your script section, include the method 'captureInputEvent' to handle the input value.

<script>
...
methods:
captureInputEvent(value){
console.log(value)
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilize binding in ReactJS to maintain the correct context

I'm currently learning how to update states in ReactJS by following a tutorial. In the tutorial, I came across this line of code: this.updateLanguage = this.updateLanguage.bind(this). Although I grasp the basics of 'this' and 'bind&apos ...

Ways to remove specific characters from the escape() function in express-validators

When using the check method from express-validator to validate user input, I'm curious if there's a way to exclude certain characters from the test. For example, currently I have: check("profile.about").trim().escape() This code snippet convert ...

Unable to navigate through select2 dropdown if fixed div is present

I am facing an issue with select2 in my fixed div popup that acts like a modal. The problem is that when the select2 dropdown is open, I am unable to scroll the div until I close the dropdown. This becomes problematic on smartphones because the keyboard e ...

Inject Angular 2 component into designated space

I am working on a website that requires a settings dialog to be loaded in a designated area upon clicking a button. The settings dialog is a component that retrieves data from REST endpoints. I am hesitant to simply insert the component and hide it as I ...

Why won't my setTimeout function work?

I'm having trouble working with the setTimeout function, as it doesn't seem to be functioning properly. First and foremost, Player.prototype.playByUrl = function (url) { this.object.data = url; return this.play(); } The co ...

Using nested ternary operations in React can cause issues with accessing local variables

Note: I encountered an issue where the extra curly braces around the first ternary result did not solve my initial problem. I replaced them with parentheses. Josep's suggestion to use getTime required me to equate the dates. The Date().setHours(0, 0, ...

Error: The Mui Material Breakpoints Theme Cannot Be Located

Hello there! I'm having some trouble placing my code breakpoints, resulting in an error in the output. Can you help me? import { makeStyles } from "@material-ui/styles"; const useStyle = makeStyles((theme)=>({ LogoLg:{ display:&ap ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Loading Bootstrap accordion content with AJAX only when clicked

Is there a way to load ajax content into an accordion only when it is active? This could help prevent unnecessary data loading. It would be helpful to have a spinner displayed while the content is loading. I've searched online but haven't found a ...

Unable to dismiss message in Django

I'm a beginner in Django and I recently followed a tutorial to add message alerts to my code. The alerts are displaying correctly, but unfortunately, I am having trouble closing them using the 'x' button. https://i.stack.imgur.com/BQS1S.png ...

Authentication in Feathers JS without the need for email addresses

Currently, I am in need of an authentication system for my dApp that operates without using email addresses or storing any user information. What I require is an endpoint where users can submit a seed phrase and password to generate a JWT. The process shou ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

"Which is the better choice for a Django application's for loop: views.py or

I'm in the process of creating a Django app that features a word list. The app currently utilizes a speech function to inform the user of the first word on the list. The user is then able to record an audio clip of a word they say, which is converted ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Is there a way to redirect links within an iframe when a user decides to open them in a new tab?

I am currently developing a web application that allows users to access multiple services, such as Spark and others. When a user selects a service, like Spark for example, the app will open a new tab displaying my page (service.html) with user information ...

Maintain consistent theme across various pages using javascript

So I successfully implemented a dark mode on the front page using the following script (sourced from W3schools) : <script> function darklightmode() { var element = document.body; element.classList.toggle("dmode"); } </script> ...

When using the `Document.write()` method, an error is returned stating, "Uncaught TypeError: Cannot read property 'document' of null"

I am currently integrating Angular2 into a website as the front-end framework, and it will be displayed on another website using an iframe. When working with the HTTP post method, I am able to receive a JSON response. Here is the API Post method that retu ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Troubleshooting the 'ReferenceError: requestAnimationFrame is not defined' error in Vuetify unit testing

Running vue run test:unit with certain Vuetify components is resulting in the error outlined below: ReferenceError: requestAnimationFrame is not defined at VueComponent.mounted (dist/js/webpack:/src/components/VTextField/VTextField.ts:229:1) a ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...