What is the best way to input variables specified in script setup for conducting unit tests?

In my component, I am utilizing a reactive state that is defined within the script setup section:

const state = reactive({
    hello: 'world'
})

This state can be accessed in tests in this manner:

wrapper.vm.state.hello = 'mad-world'

Unfortunately, when using TypeScript checks, the variable types in the vm are not recognized, resulting in an error:

test/unit/components/price/my-component.test.ts:56:16 - error TS2339: Property 'state' does not exist on type 'MyComponent & { $: ComponentInternalInstance; $data: {}; $props: {}; $attrs: Data; $refs: Data; $slots: Readonly<InternalSlots>; ... 7 more ...; $watch<T extends string | ((...args: any) => any)>(source: T, cb: T extends (...args: any) => infer R ? (args_0: R, args_1: R) => any : (...args: any) => any, options?: Wat...'.

56     wrapper.vm.state.hello = 'mad-world'

The type declaration for this component is as follows:

export interface MyComponent extends ComponentPublicInstance {
    state: {
        hello: string
    }
}

It is used in the test setup like this:

let wrapper: VueWrapper<MyComponent>

beforeEach(async () => {
    wrapper = mount({ ... }) as VueWrapper<MyComponent>
})

While it is possible to expose these variables from the data method within the traditional script tag, this cannot be done with the script setup.

Answer №1

In my opinion, relying on testing the internal implementation details is not a recommended practice. It's better to focus solely on the component's public API such as props, slots, and emitted events. If you want to achieve type inference for components created using the script setup syntax, you can utilize the defineExpose macro like this:

<script setup lang="ts">

const data = reactive({
    message: 'hello world'
})

defineExpose({
  data,
})
</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

The disabled attribute appears to be ineffective in an Angular reactive form

In my Angular reactive form, I have an email field that I want to disable when the form is in edit mode instead of add mode. The code I am using for this is: disabled: typeof user.user_id === 'string' When I debug the modelToForm method and che ...

Ignoring setTimeout() function within forEach() in Angular leads to issues

I am currently working on the frontend development of a Web Application using Angular. My task involves saving data from an array into a database by making repeated API calls until all the array data is processed. I implemented the use of setTimeout() in ...

What is the most effective method for transmitting data within your Vue3 application?

What is the best way to pass data between Vue components? I am looking for a method that allows me to fetch data from the backend once and share it across my project seamlessly, but I can't seem to find the right approach. sessionStorage: It works we ...

Component updates are not working in VueJS

My Vue 1 component requires an object as a prop that needs to be filled by the user. This object has a specific structure with properties and nested inputs. The component is essentially a modal with a table containing necessary inputs. I want to perform v ...

Angular controller unit testing is an essential practice in software development

I am currently working with an angular module named 'widgets'. In my app, I have used its signature as follows: var app = angular.module('widgets', [ 'widget.Panel', 'widget.List', 'services' ] ...

What is the top frontend framework and which one seamlessly integrates with various backend frameworks?

When it comes to frontend frameworks, JavaScript acknowledges three major players: React, Angular, and Vue.js. Each of these frameworks offers ease of understanding, learning, and implementation. Now the question arises - which one is most compatible wit ...

What is the best way to retrieve an empty instance using a getter in Vuex?

My store has a default setting that returns undefined for a specific attribute: // store.js export const state = { locationLoading: false, locationsLoading: false, locations: [], location: undefined, <-- }; In my component, I am utiliz ...

having trouble displaying array data in a table using vuejs

Hey everyone, I'm encountering an issue with this table not displaying the data. It seems like axios is fetching the data correctly and logging it in the console, but for some reason, it's not showing up in the table. <table id="app"> ...

Struggling to make type definitions work in react-hook-form 7

Upon defining the types of my form fields, I encountered an issue where each field seems to take on all three different types. This is puzzling as I have specified 3 distinct types for my 3 different fields. What could be causing this confusion? https://i ...

Getting a variable from the server (process.env.SERVER) and passing it to the browser in Vue

There is a file that can be read on the frontend server using the following code: if(!!process.env.SERVER) { require("dotenv").config( { path: '/hw/.env', debug: true } ) console.log(process.env.myvar) } I'm curious, how can I ...

issues with firebase dependencies no longer functioning

My Vuejs app has been running smoothly with Firebase Authentication, but today I encountered an issue. Upon starting the app (npm run serve), I am now facing the following error: These dependencies were not found: * firebase/app in ./src/helpers/firebase. ...

Authenticate users using Laravel's default authentication system, then serve the Vuejs single page application only to logged

Currently working on a Single Page Application using the default Laravel scaffolding: // Setting up basic scaffolding... php artisan ui vue // Implementing login / registration features... php artisan ui vue --auth These commands provide a solid foundati ...

Passing a value from a function to a label for a checkbox input in Vue.js3 will allow the label to dynamically change based on the boolean value of

<template> <div> <input @change="change($event)" type="checkbox" id="check" v-model="checked" class="toggle" /> <label for="check" >{{ status }}</la ...

The functionality of linear mode seems to be malfunctioning when using separate components in the mat-horizontal-stepper

In an effort to break down the components of each step in mat-horizontal-stepper, I have included the following HTML code. <mat-horizontal-stepper [linear]="true" #stepper> <mat-step [stepControl]="selectAdvType"> <ng-template matStep ...

How can you refer to the implementing class from an interface in TypeScript?

Delving into the Typescript type system, I am currently working on implementing the Fantasy Land Spec and encountered a hurdle while trying to implement the specification for Semigroup. The spec dictates that a Semigroup must follow the type definition ou ...

Error encountered in azure devops preventing successful execution: "npm ERR! code ELIFECYCLE"

I am facing an issue with my Azure DevOps build pipeline that contains 2 npm tasks: - one for npm install - and the other for npm run-script build Unfortunately, I am encountering errors that do not provide sufficient information about the root cause of ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

VueJS in collaboration with Quasar framework

Incorporating VueJS with Quasar framework, I created a data table. Here is my implementation: <template> <div class="q-pa-md"> <q-table title="Task List Of The Day" :columns="columns" row-key="name" :pagination ...

Utilizing a d.ts Typescript Definition file for enhanced javascript intellisene within projects not using Typescript

I am currently working on a TypeScript project where I have set "declaration": true in tsconfig.json to generate a d.ts file. The generated d.ts file looks like this: /// <reference types="jquery" /> declare class KatApp implements IKatApp ...

Exploring ways to retrieve a video thumbnail with VueJS3

I am currently working on a project to create a simple program that retrieves movies from my AWS-S3 bucket and transforms them into picture thumbnails. Below is the code I have written: <template> <img :src="imgURL" class="card- ...