Putting VueJS, typescript, and jest to the test: examining the contents of a dropdown list web-component

Currently, I am in the process of testing a dropdown list within a web component utilized in a VueJS application.

My main focus is on checking whether the dropdown list actually contains items fetched through an HTTP query (handled in a vuex store) once the created() lifecycle hook of the application is activated.

The VueJS application that I am working with is coded in typescript and for my testing purposes, I rely on Jest as my preferred framework.

Below is my Vue component named SearchBar.vue that requires testing:

<template>
    <dropdown-web-component
        label="Applications"
        :options.prop="applications"
    />
</template>

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

@Component
export default class SearchBar extends Vue {
    get applications() {
        return this.$typedStore.state.applications;
    }
    created() {
        // The HTTP call functionality is implemented within the vuex store
        this.$store.dispatch(Actions.GetApplications);
    }
}

Answer №1

After much trial and error, I finally managed to get it working:

The testing script SearchBar.spec.ts was crucial for testing the component:

import Vuex, { Store } from "vuex";
import { shallowMount, Wrapper } from "@vue/test-utils";
import SearchBar from "@/components/SearchBar.vue";
import { Vue } from "vue/types/vue";

describe('SearchBar', () => {
    let actions: any;
    let store: Store;
    let state: any;

    beforeEach(() => {
        const applications = ['applicationId1', 'applicationId2', 'applicationId3'];

        actions = {
            GET_APPLICATIONS: jest.fn()
        };
        state = {
            applications
        };
        store = new Vuex.Store({
            modules: {
                users: {
                    actions,
                    state
                }
            }
        });
    });

    it('should trigger the GET_APPLICATIONS vuex store action upon creation', () => {
        shallowMount(SearchAndFilterBar, { store });

        expect(actions.GET_APPLICATIONS).toHaveBeenCalled();
    });

    describe('Applications dropdown', () => {
        it('should display a dropdown menu with all applications', () => {
            const wrapper = shallowMount(SearchAndFilterBar, {
                store
            });
            const filter: Wrapper<Vue> = wrapper.find('dropdown-web-component');
            
            // To prevent TS errors, casting to any is necessary
            expect((filter as any).vnode.data.domProps.options.length).toEqual(3);
        });
    });
});

I truly hope that my own solution can assist others, as uncovering these nuances took considerable effort on my end.

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 is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

What is the reason that the 'updated' function for a component does not trigger when there is a modification made to an array prop?

After creating a child component with a single prop of type Array, I expected the updated lifecycle event to be triggered whenever that array was modified from the parent by using push(). However, this is not happening. While I can observe the changes taki ...

Ways to modify the appearance of an element depending on various data sources

One issue I have encountered is the need to display different icons on a user's profile page based on their status. The possible statuses are as follows: 0 - guest user 1 - registered user with unverified email 2 - registered user with verified email ...

The TypeScript compiler generates a blank JavaScript file within the WebStorm IDE

My introduction to TypeScript was an interesting experience. I decided to convert a simple JavaScript application, consisting of two files, into TypeScript. The first file, accounts.ts, contains the main code, while the second one, fiat.ts, is a support f ...

Troubleshooting problem with Laravel and Vue integration

I have experience working on a Laravel and Vue.js project. Here is the code snippet for the Laravel view: @extends('layouts/app') @section('content') <div id="app"> </div> @endsection And here is the ...

The process of testing the catch part in jest and @testing-library/react

ComponentFile.js <Button onClick={ async e =>{ clearForm(); }} Reset </Button> const clearForm = () => { try{ someRef.current.clearFormData(); const display = document.getElementById("errorDisplayDi ...

Record the actions emitted by child components

I am struggling to respond to an action emitted by a child component. The child triggers an event/action called init. I try to listen for this event in the parent component's events mapping. However, the callback function never executes, leading me to ...

An effective way to extract targeted information from an array of objects using Typescript

I'm having trouble extracting the IDs from the selected items in my PrimeNG DataTable. Despite searching on Google, I couldn't find much information about the error I'm encountering... ERROR in C:/Users/*****/Documents/Octopus/Octopus 2.0/s ...

Precisely outline the function type that operates on an object, makes changes to its values, and then outputs the object in TypeScript

Can anyone help me create a function that generates a new object with the same keys as the input object, but with all values set to null? Here's the existing code: function nullify(arg) { var returnObj = {} for (var key in arg) { returnObj[ ...

Is it possible to assign default values to optional properties in JavaScript?

Here is an example to consider: interface Parameters { label: string; quantity?: number; } const defaultSettings = { label: 'Example', quantity: 10, }; function setup({ label, quantity }: Parameters = { ...defaultSettings }) { ...

What steps can I take to generate a Vue instance using Jest when encountering an error message stating that "Vue

I need to troubleshoot a code that combines Vue and jQuery. The code makes use of jQuery to make REST API calls, and then the returned JSON data is processed with Vue. However, there seems to be an issue with it. During testing, I encountered the follow ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

The entire React component is not rendering as expected when calling res.render in PugJS within Express

Seeking guidance for the following issue: I have developed a PugJS view that is rendered within an ExpressJS route. In the call to the ExpressJS function res.render, the React component is included as data inside the .render() function call.... The prob ...

Steps to arrange by the number of rows in ag grid

I've been experimenting with the rows group feature in ag-grid, But I'm curious if it's feasible to sort the group column based on the number of rows within each group? Here is an example of what I am trying to achieve: ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

I'm sorry, we couldn't locate the module: Unable to find the path '../types/index'

After spending an hour attempting to troubleshoot this issue, I am still unable to find a solution. I have stored index.d.ts in the types folder. The content of the types file is as follows: export interface tag { created_at: string id: nu ...

After updating my Angular version from 8 to 9, an error has been thrown stating "It is not possible to assign the value 'undefined' to the template variable 'limit'"

Recently, I made updates to my Angular 8 project by switching it to the newest version of Angular 9. In one of the template's div elements, I declared a variable and everything seemed to be functioning correctly without any errors. To avoid initializi ...

Displaying column values in Vuetify Table based on a condition

https://i.stack.imgur.com/wK9uU.png I'm working with a Vuetify table that has a column for URLs. I need to implement logic to display either the URL or the URL Group name based on properties in my rules array. If rules[i].urlGroup is not empty, then ...

Easiest Angular Carousel Solution

My goal is to create a basic Angular Carousel to enhance my understanding of Angular. While I have received helpful answers in the past, I am seeking further clarification to deepen my knowledge of Angular2+ and Typescript. Here's what I have so far: ...

When trying to access the key value of a dynamically generated object, it returns as undefined

I am facing a challenge with my student object structure... { Freshmen: [{id: 3}, {id: 5}], Sophomores: [{id: 2}, {id: 6}], Juniors: [{id: 1}, {id: 8}], Seniors: [{id: 9}, {id: 4}, {id: 7}] } My goal is to retrieve full student objects from the d ...