The function cannot be accessed during the unit test

I have just created a new project in VueJS and incorporated TypeScript into it.

Below is my component along with some testing methods:

<template>
    <div></div>
</template>

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

@Component
export default class Slider extends Vue {
  private slide: number = 0;
  private sliding: boolean = false;

  public setSlide(slide: number): void {
    this.slide = slide;
  }

  public setSliding(sliding: boolean): void {
    this.sliding = sliding;
  }

  private onSliderStart(slide: any): void {
    this.setSliding(true);
  }

  private onSlideEnd(slide: any): void {
    this.setSliding(false);
  }
}
</script>

To run the tests:

import { shallowMount } from '@vue/test-utils';
import Slider from '@/components/Header.vue';

describe('Slider', () => {
  const wrapper = shallowMount(Slider);

  it('Check if Slider is an instance of Vue', () => {
    expect(wrapper.isVueInstance()).toBeTruthy();
  });

  it('Verify that setSlide is a function', () => {
    expect(typeof wrapper.vm.setSlide).toBe('function')
  })
});

As I proceed to conduct the test, I notice that the methods setSlide and setSliding are not available in the wrapper.

Answer №1

Give this a try:

import YourComponentHere from "@/components/YourComponentHere";
import { shallowMount, Wrapper } from "@vue/test-utils";

describe("test", () => {
  const wrapper: Wrapper<YourComponentHere & { [key: string]: any }>;
  it("performs some action", () => {
    expect(wrapper.vm.someThingWhatever).toBe(true);
  });
});

An added benefit is that there's no need to constantly cast wrapper.vm to any whenever you access wrapper.vm

Answer №2

To avoid TypeScript errors, you may need to explicitly cast wrapper.vm as type any:

it('setSlide is func', () => {
  expect(typeof (wrapper.vm as any).setSlide).toBe('function')
})

You can also declare the wrapper variable as type any at the beginning of your tests:

const wrapper: any = shallowMount(Slider);

Resource: https://github.com/vuejs/vue-test-utils/issues/255#issuecomment-433312728.

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

Using hooks for conditional rendering

Background Information : My current project involves creating a form using hooks and rendering components based on the step. Challenge Encountered : I received this error message: "Error: UserFormHooks(...): Nothing was returned from render. This usually ...

Utilizing v-for with keep-alive in Vue3

Issue at Hand I have a varying number of Tab components; the count can range from 1 to 10, but only one is visible at any given moment. Nonetheless, I aim to retain them in memory during switches. My initial thought was to utilize a v-for loop within a &l ...

Ensure to pass the correct type to the useState function

I have a basic app structured like this import React, { useState } from 'react' import AddToList from './components/AddToList' import List from './components/List' export interface IProps{ name: string age: number url: ...

ajax call triggering knockout foreach update

Within my ViewModel, I have defined a variable called self = this; Another foreach binding is working in my code, but it is not within an ajax request. The initial UI load is functioning correctly. I have confirmed that self.wikiData is being updated by ...

Unit Testing in Angular with spyOn().and.callThrough() does not execute the actual function

I am new to unit testing using Jasmine in Angular and currently exploring how to test a service with the function loadSomething(id) and added a console.info statement in it. My Service Code: function loadSomething(id) { console.info('this is a t ...

Tips for utilizing the polymorphic feature in TypeScript?

One of the challenges I am facing involves adding data to local storage using a function: add(type: "point" | "object", body: FavouritesBodyPoint | FavouritesBodyObject) { // TODO } export interface FavouritesBodyPoint {} export in ...

Initiating a node request utilizing the value of the array index as the req parameter

I created a method to insert a series of documents into a mongoose collection, with each entry containing the value corresponding to the next index in a range specified by upper and lower bounds. The current implementation works seamlessly when the lower ...

Configuring Tailwind CSS with PostCSS in a Nuxt project

Error Message "In order to avoid issues with features like alias resolving inside your CSS, please make sure to use build.postcss in your nuxt.config.js file instead of an external configuration file. Support for external config files will be depreca ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...

Runs tasks asynchronously in a sequential manner

I am attempting to run two functions asynchronously in series using node.JS, but I am struggling with the implementation. Currently, my code looks like this: Function 1: function search(client_id, callback) { clientRedis.keys('director:*', ...

What are the steps for implementing pytesseract on a node.js server?

While working on my node.js server, I encountered an issue when using child-process to send an image to a python script. Although I can successfully read the image in the python script, I encounter an error when attempting to convert it to text using pytes ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

What sets apart gzip from x-gzip content? And how can I decompress x-gzip specifically? zlib appears to be struggling

One of my npm libraries, named "by-request", has the ability to auto-decompress web content. A snippet of code from this library that handles auto-decompression is shown below: if (!options.dontDecompress || !binary) { if (contentEncoding ...

Mapping DOM elements to VueJS components for hydration is a key process in facilitating

I have a specific requirement and I am exploring potential solutions using VueJS, as it offers the convenient feature of hydrating pre-rendered HTML from the server. In my Vue components, I do not define a template within the .vue file, but I need them to ...

Tips for managing erroneous data in csv files using Node.js

I am currently working on an application that parses csv files using the csv module. It is functioning well, but I am facing a problem where if there is a bad row in the csv file, the entire process fails. Is there a way to skip bad rows and continue stre ...

Sequelize is unable to retrieve a table from the database

I am configuring Sequelize in order to streamline the manipulation of an MSSQL database. My attempt to define a table called 'Stock' has resulted in unexpected behavior when trying to query it. Below is the code snippet I used for defining the t ...

Issue encountered during Heroku deployment: Failed to build React app. When attempting to push changes to Heroku, an unexpected end of input error was received instead of the expected result. This error occurred on an unidentified file at

Encountering a parsing error while attempting to deploy a React app on Heroku using git push heroku master. The app built successfully yesterday, but since then some media queries were added by another contributor to various .scss files. The primary error ...

Ajax encounters difficulty in parsing JSON data

I have thoroughly researched similar questions on this topic, but none of them have provided a solution to my problem. My current challenge involves parsing JSON data that is being returned from a PHP script running on the server. I have already used JSON ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...