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

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

My Discord bot powered by Discord.js is being unresponsive to commands

Hello, I'm facing a major issue with my command handler that I've been struggling with for a while now. The problem is that my bot doesn't respond when I try to use a command. I've tried various methods from YouTube but none of them see ...

During the build process, Next.js encounters difficulty loading dynamic pages

My Next.js application is utilizing dynamic routes. While the dynamic routes function properly in development mode, I encounter a 404 error when deploying the built app to Netlify. https://i.stack.imgur.com/45NS3.png Here is my current code setup: In _ ...

Guide on incorporating JavaScript code within a PDF document

Looking for guidance on implementing JavaScript in PDF files I am seeking advice from those familiar with adding JavaScript actions to PDF documents, as this is a new area of exploration for me. While I have experience with JavaScript in web development, ...

Steps for displaying innerHTML values conditionally with a pipe

Currently working with Angular 8 and looking to conditionally implement the innerHTML feature using a translation pipe. .html <button type="button" mat-flat-button // utilizing translate module internally [innerHTML] = "display ? (HIDE ...

Vue component's property does not exhibit reactivity

I seem to have encountered an issue with Vue.js, or perhaps I am missing something fundamental. In the simple example provided below, there appears to be a bug that I am able to replicate. The App.vue component includes a reactive variable called message, ...

Using AJAX to transform octet-stream into typed array (Float64Array)

I can't seem to figure out where I'm going wrong here. My attempt involves converting a binary stream obtained from an AJAX request into an array of doubles using JavaScript. Here is some of my code: The PHP script on my server returns an octet-s ...

How can I prevent list items in jQuery Mobile from being truncated with ellipses?

Here is the list I am working with: <ul id="linksList" data-role="listview" data-inset="true" data-filter="true"> <!-- Dynamic contents! --> </ul> This list pulls its data from a local XML file (RSS feed). I am looking f ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

Use Express JS to enable users to upload their profile picture either during account creation or on the registration form

Just starting out with node js, I'm working on a basic app where users can create accounts with their details. I've implemented mongo dB as the backend to store user information such as names and emails. Once an account is created, users are dir ...

Converting a Luxon DateTime object into a standard date

Currently, I am constructing a DatePicker React component utilizing the Material-UI picker library and integrating Luxon as an adapter. Whenever I modify the calendar date, I receive an object containing DateTime information as shown below: This is the co ...

Discover the power of uploading images using HTML5 with PHP

Is there a way to retrieve values of uploaded images after clicking on the submit button using $_POST in PHP (with image upload through HTML5)? For an example of HTML5 image upload, you can check out this link You can access the demo at the following lin ...

IE may not support the use of XMLHttpRequest with the POST method

When interacting with a server through an XMLHttpRequest to post data, the code typically follows this structure: var xhr = new XMLHttpRequest(); var url = 'http://myurl/post'; xhr.open("POST", url, true); xhr.setRequestHeader("Content-type", " ...

ADVENTURE BLOCKED - Intercept error: net::ERR_BLOCKED_BY_CLIENT

I've encountered an issue where my initialize function doesn't run properly when a user has an ad blocker enabled. It seems that the ads-script.js file is being blocked by the client with a net::ERR_BLOCKED_BY_CLIENT error, leading to my .done ca ...

The Oracle Database listener is unaware of the service specified in the connect descriptor for node-oracledb

Having recently transitioned from on-premise databases using Oracle 11g to the Cloud where I needed to connect to Oracle 12c, I encountered an issue with my nodejs application. While it worked fine on-premises, in the cloud it threw the following error: e ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

How can I convert a string into JSON format in Node.js?

Imagine this scenario: a HTTP REST API has just sent me a JSON in the form of a string. How can I transform it back into a structured JSON object? ...

How can I handle moving to button code-behind when validation fails without relying on Page.IsValid?

Recently, I encountered a challenge with an ASP.NET page that contains both ASP.NET validators and JavaScript checks. As I delved into the button code behind the scenes: protected void Button2_Click(object sender, EventArgs e) { if (Page.IsVal ...

The performance implications of implicit returns in Coffeescript and their effects on side effects

Currently, I am developing a node.js web service using Express.js and Mongoose. Recently, I decided to experiment with CoffeeScript to see if it offers any advantages. However, I have come across something that has left me a bit unsettled and I would appre ...

When clicking on links that are not within the ng-view element, you will be redirected to the

I'm having trouble coming up with a name for this question, but here's my current situation This is the structure of my template: ├── index.html ├── ... ├── account │ ├── index.html │ ├── authorizat ...