Performing unit testing on a Vue component that relies on external dependencies

Currently, I am in the process of testing my SiWizard component, which relies on external dependencies from the syncfusion library. The component imports various modules from this library.

SiWizard.vue Imports

import SiFooter from "@/components/subComponents/SiFooter.vue";
import { Prop, Component, Vue } from "vue-property-decorator";
import { TabPlugin, TabComponent, SelectingEventArgs } from "@syncfusion/ej2-vue-navigations";
import { VNode } from "vue";

Vue.use(TabPlugin);

In order to simplify things, I have created a test case using vue js test utils and jest. The aim is for this test to pass by configuring a single prop.

siWizard.spec.ts

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

let wrapper: Wrapper<SiWizard & { [key: string]: any }>;

describe("testing SiWizard", () => {
  test("Test add mode", () => {
    wrapper = shallowMount(SiWizard, {
      propsData: {
        mode: "add"
      }
    });

    expect(true).toBe(true)
  });

During the execution of siWizard.spec.ts, I encountered some strange errors. Error without mocking, test still passes

My assumption is that the properties in the test environment are unable to access the dependency properties utilized in the SiWizard component. Therefore, I attempted to mock the TabPlugin using Jest. Subsequently, I tried mocking the dependency with jest.mock.

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

// import { TabPlugin } from "@syncfusion/ej2-vue-navigations";

jest.mock("../../node_modules/@syncfusion/ej2-navigations" , () => { jest.fn() });

let wrapper: Wrapper<SiWizard & { [key: string]: any }>;

describe("testing SiWizard", () => {
  test("Test add mode", () => {
    wrapper = shallowMount(SiWizard, {
      propsData: {
        mode: "add"
      }
    });

    expect(true).toBe(true)
  });

The end result was a failing test with the following error message Error and failing test

Uncertain if the need for mocking is necessary since the initial test still passes but continues to display errors. Can someone advise me on whether my mocking approach is correct or if there is something else I should be doing?

Answer №1

Insert this code snippet at the beginning of your testing document:

jest.mock("../../node_modules/@syncfusion/ej2-navigations")

Answer №2

We apologize for the delay in responding to your query.

After investigating the issue you reported, we have successfully replicated it on our end. Our team is currently working on finding a solution and will update you with the necessary details. In the meantime, we recommend using karma unit testing with Mocha and you can access a sample project by clicking on the following link:

Sample:

Here is the code snippet:

NPM Packages:

npm install --save-dev karma karma-chrome-launcher karma-mocha karma-sourcemap-loader karma-spec-reporter karma-webpack mocha

./tests/unit/example.spec.ts

import { expect } from 'chai'
import Vue from "vue";
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  let vm: any;
  let dropdown: any;
  beforeEach(() => {
    vm = new Vue({
      el: document.createElement("div"),
      render(h) {
        return h(HelloWorld);
      },
    });
    dropdown = vm.$children[0].$refs.dropdownElement;
  });

  afterEach(() => {
    vm.$destroy();
  });


  it('checking default value of dropdown', () => {
    expect(dropdown.value).to.equal('Badminton');
  })

  it('changing the value of dropdown', () => {
    let vm1: any = vm.$children[0].$data;
    vm1.selectedValue = 'Cricket';
    Vue.set(vm1, 'selectedValue' , 'Cricket');
    Vue.nextTick().then(()=>{
      expect(dropdown.value).to.equal('Cricket');
    });
  })

})

Feel free to reach out if you require any further assistance.

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

Replace a portion of text with a RxJS countdown timer

I am currently working on integrating a countdown timer using rxjs in my angular 12 project. Here is what I have in my typescript file: let timeLeft$ = interval(1000).pipe( map(x => this.calcTimeDiff(orderCutOffTime)), shareReplay(1) ); The calcTim ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...

Tips for positioning bootstrap-vue dropdown button items evenly

Can anyone help me align the dropdown button child items horizontally? I've tried customizing it with CSS but no luck. The control link can be found here Check out a sample on Js Fiddle here This is how I expect the design to look like: new V ...

Can one obtain a public IP address using Typescript without relying on third-party links?

Though this question has been asked before, I am currently working on an Angular 4 application where I need to retrieve the public IP address of the user's system. I have searched on Stackoverflow for references, but most posts suggest consuming a th ...

Learn how to utilize Vue 3 to access properties that have been passed down from a parent component, even if they

Hey there, hope everything is going well. I'm familiar with react.js, but when I gave vue a try, things felt a bit different. In react, it's easy to access props passed from the parent in the child component without much hassle. However, in vue, ...

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

The problem with the Custom Select Component: Error Arises When Utilizing the Generic Type <T,> with a Comma as Opposed to <T> Without a Comma

I recently developed a unique custom select component that extends the standard HTML select element. During the process, I made use of a generic type to accommodate a wide range of data types, but encountered an unexpected error. The issue seems to persist ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Tips for integrating and utilizing the MSAL (Microsoft Authentication Library for JavaScript) effectively in a TypeScript-based React single page application

Issue I'm encountering difficulties importing the MSAL library into my TypeScript code. I am using the MSAL for JS library with typings in a basic TypeScript/React project created using create-react-app with react-typescript scripts. As someone who i ...

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

What is the process of assigning a value type to a generic key type of an object in typescript?

I am currently working on developing a function that can merge and sort pre-sorted arrays into one single sorted array. This function takes an array of arrays containing objects, along with a specified key for comparison purposes. It is important to ensure ...

Exploring the Variance between 'npm run serve' and 'npm run dev' Commands in Vue.js Development

Can you explain to me the distinction between npm run serve and npm run dev in vuejs? Additionally, can you clarify why it is recommended to use the npm run serve command when running a project? ...

Looking to tweak the date format in a Vue.js template?

I received the following format: 2019-01-08T11:11:00.000Z However, I need it to be in this format: 2019-01-08 Does anyone know how to achieve this date formatting without using the moment package? ...

Spartacus storefront is having trouble locating the .d.ts file when using Angular/webpack

Seeking help from the SAP Spartacus team. Encountering errors while developing a Spartacus component, specifically with certain Spartacus .d.ts definition files that cannot be resolved. The issue is reproducible in this Github repository/branch: This pr ...

Display a webpage once its design is completely loaded in Nuxt

I have implemented a layout for my admin pages that displays user information in a consistent format, eliminating the need to fetch this data every time the page reloads. However, I am facing an issue where the page does not wait for the layout to fully l ...

Resource is used to return an array as an object

There is something peculiar going on. I have come across an array structured like this: => [ "optionalinformation" => [ "domain" => [ "type" => "string", ], ], ] This particular array is utilized by a reso ...

What is the best way to dynamically import and utilize multiple components in Nuxt?

In my Nuxt + CMS setup, I am looking to implement dynamic pages. When I send the URL to the server, I should receive data if a corresponding page exists. The data includes a varying list of components that need to be utilized on the page. To achieve this, ...

Using Vue, the placeholder attribute can be set for a base input label

Looking for some assistance with debugging this issue. I have two components, BaseInput and BaseTextarea. For the input and textarea elements, I am adding the placeholder attribute as needed. All other attributes are being added to the label element. Wh ...

Establishing the types of object properties prior to performing a destructuring assignment

Consider a scenario where a function is utilized to return an object with property types that can be inferred or explicitly provided: const myFn = (arg: number) => { return { a: 1 + arg, b: 'b' + arg, c: (() => { ...

using vuejs to pass a function as a prop

As I work on creating a foundational "TableComponent," incorporating selectable rows and more, I am faced with the requirement for this TableComponent to accept a prop named "buttons." These buttons are expected to be in the form of an array of objects ...