Exploring VueJs 3's Composition API with Jest: Testing the emission of input component events

I need help testing the event emitting functionality of a VueJs 3 input component. Below is my current code:

TextInput

<template>
  <input v-model="input" />
</template>
<script>
import { watch } from '@vue/composition-api';
export default {
  name: 'TextInput',
  props: {
    value: {
      default: '',
    },
  },
  setup (props, { emit }) {
    let input = ref(props.value);
    watch(input, value => {
      emit('input', value);
    });
    return { input };
  }
};
</script>

text-input.spec.js

import { shallowMount } from '@vue/test-utils';
import { TextInput } from '@/src/index';

describe('TextInput test', () => {
  it('Emits input event', async () => {
    const wrapper = shallowMount(TextInput);

    const input = wrapper.find('input');
    input.setValue('Jon');
    input.trigger('keyup');

    await wrapper.vm.$nextTick();

    const emitted = wrapper.emitted('input');

    expect(emitted).toHaveLength(1);
    expect(emitted).toEqual(['Jon']);
  });
})

When running the test, I encounter the following error:

● TextInput test › Emits input event

    expect(received).toHaveLength(expected)

    Matcher error: received value must have a length property whose value must be a number

    Received has value: undefined

      52 |     const triggeredEvent = wrapper.emitted('input');
      53 |
    > 54 |     expect(triggeredEvent).toHaveLength(1);
         |                            ^
      55 |     expect(triggeredEvent).toEqual(['Jon']);
      56 |   });
      57 | });

After console logging emitted, it returns an empty object {}.

Answer №1

After struggling for a while, I finally found a solution by carefully reading through one of the answers on Issue #202 during testing.

The key was to direct Vue to utilize the composition API and make slight adjustments to my assertions.

import Vue from 'vue';
import { TextInput } from '@/src/index';
import { shallowMount } from '@vue/test-utils';
import CompositionApi from '@vue/composition-api';

Vue.use(CompositionApi);

describe('Testing the TextInput component', () => {
  it('Should emit input event correctly', async () => {
    const wrapper = shallowMount(TextInput);

    const input = wrapper.find('input');
    input.setValue('Jon');
    input.trigger('keyup');

    await wrapper.vm.$nextTick();

    const emitted = wrapper.emitted('input');

    expect(emitted).toHaveLength(2);
    expect(emitted[1]).toEqual(['Jon']);
  });
})

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

Unforeseen execution issues arising from repeated Ajax calls with SetTimeout in JavaScript

I have a list of users displayed in an HTML table that is dynamically created on page load. Each row includes an inline button with onclick="functionName(userId)" that triggers the following actions: When clicked, a Bootstrap modal popup is shown and the ...

What is the jQuery equivalent for converting this JavaScript code?

Here's a code snippet that I am struggling with: data=>{document.querySelector( "#os11.html-widget.gauge svg text[font-size='10px'] tspan" ).innerHTML = data.text I attempted the following solution: $("#os11.html ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

What is the process for removing the body of a table?

My goal is to reset the table body, which has been filled with JavaScript loaded data previously. https://i.stack.imgur.com/7774K.png ` getTableData = function (clicked_id) { if (clicked_id != '') { $.ajax({ async : f ...

JavaScript is providing HTML output instead of JSON results

Recently, I have been facing an issue with connecting to bitbucket and collecting the commits. The code snippet that I used is as follows: import fetch from 'node-fetch'; async function fetchData(){ await fetch('https://bitbucketexam ...

Avoid using the Router with the Search component in React JS

Having trouble rendering my Search component within the main Header component using react-router-dom. I suspect there's an issue with this line of code <Route render={({ history }) => } /> I've been stuck on this for two days now... T ...

Dealing with Javascript exceptions and sending email notifications in Django

I appreciate the traditional method of handling server-side exceptions in Django using Python. I am interested in finding a similar approach for client-side exception handling in JavaScript. So far, I have come across only one option which is DamnIT, but ...

Tips for refreshing a page in Vue.js

I am facing an issue with updating a table on my page after deleting a row. Each row in the table has a delete button and I have tried using window.location.reload() but it didn't work. </va-card> <br/> <va-card > ...

Using whitespace to format a document.write in JavaScript

I'm in the process of creating a dynamic table using JavaScript and a set of objects. I've managed to structure it, but now I require some extra white space between them, almost like tabbing them out. How can I achieve this efficiently with my cu ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

Challenges when it comes to exporting files using Firebase Cloud Functions

I've been working with Firebase Cloud Functions using JavaScript, but I'm encountering issues with the import and export statements. Is there a solution to replace them? const firebase = require('firebase'); const config = { apiKe ...

Tips for effectively sharing content on social media from your Vuejs application

I have been using the vue-social-sharing library to enable social media sharing on my website, and overall it's been working well. However, I am facing a problem where when I click the Facebook share button, it doesn't share the title, descriptio ...

When a user clicks on an image, I would like to dynamically resize it using a combination of PHP

Although I have a good understanding of CSS and HTML, my knowledge of Javascript is limited. I am looking to add an interactive element to my website where an image enlarges gradually when clicked and smoothly moves to the center of the screen in one con ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

Sending parameters in GraphQL with Typescript results in an empty set of curly braces being returned

I am new to learning GraphQL with Typescript and I am trying to pass an argument in a GraphQL function to return something dynamically. I have been struggling with this issue for the past hour and could not find any solutions. Here are the relevant code sn ...

What are the reasons for the success function not being called and what steps can be taken to correct it

Whenever I attempt to submit the post, the data is successfully sent and received by the server, but the success function never gets called. In the network inspector tab of Chrome, the connection shows as stalled with a warning: "connection is not finished ...

Tips for distinguishing between elements in React

I am facing an issue with zooming images on mouse hover using CSS. I have a code snippet that works well, but it zooms both images simultaneously. How can I differentiate between mouse movements over different elements in ReactJS? Here is the code: .styl ...

What sets apart declaring an object within data() versus inside created() in VueJs?

Can you explain the discrepancies in VueJs between these declarations? data() { return { foo = 'bar' } } and this : created() { this.foo = 'bar' } I understand that both can be accessed using 'this' i ...

The issue with the Hidden Content feature in the Slick Carousel is that it does not function correctly on the

There are some related topics worth exploring, such as: Slick carousel center class not working when going from last item to first item Despite trying various solutions, the issue still persists in my code. My goal is to have each item displayed in the ce ...