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

Accordion's second child element experiencing issues with grid properties

I have set the parent element display:"Grid" and specified the gridColumnStart for my child elements as shown below. It seems to be working correctly for the first child element, but not for the second one. Please find my code attached: return ( ...

The search functionality in the unit test could not be executed as it is

Encountering an error this.sourceAccounts.find is not a function while running unit test on an array. component.ts: sourceAccounts: Array<IObject>; nameChangedSubscription: Subscription; constructor(private accountService: AccountService) { } ngOn ...

Typescript - optional type when a generic is not given

I am hoping for optionalFields to be of type OptionalFieldsByTopic<Topic> if a generic is not provided, or else OptionalFieldsByTopic<T>. Thank you in advance for the assistance. export interface ICreateItem<T extends Topic = never> { // ...

Uniting 2 streams to create a single observable

I am in the process of merging 2 different Observables. The first Observable contains a ShoppingCart class, while the second one holds a list of ShoppingItems. My goal is to map the Observable with shopping cart items (Observable<ShoppingItems) to the i ...

I encountered an error stating "Buffer is not defined" originating from the Deode/Encode Stream Bundle.js script, not from my own code

I've encountered a major issue while attempting to update my npm project to webpack 5, and now I'm left with just one persistent error: bundle.js:1088566 Uncaught ReferenceError: Buffer is not defined at bundle.js:1044980:24 ...

Matching only the specified Records in an array of Typescript generic objects

Check out this demo: https://tsplay.dev/Nnavaw I am working with an array that has the following structure: Array<{ id?: string; text?: string; date?: Date; }> This conflicts with the current implementation: data: Array<Par ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

Loading a view in Ionic2 with Angular2 after a successful subscription

After completing an http post request, I want to navigate to the next view in my app. Here is a breakdown of the three services I am using: The server service handles generic http calls such as get and post requests. The city service stores a list of ...

Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully rec ...

What is the best way to create a new row within a Bootstrap table?

Struggling to format an array inside a table with the `.join()` method. The goal is to have each car on a separate row. Attempts using `.join("\r\n")` and `.join("<br />")` have been unsuccessful. What am I overlooking? ...

Zod combinator that accepts a dynamic field name

When converting XML to JSON, my library outputs {MyKey: T} for single-element lists and {MyKey: T[]} for multi-element lists. The equivalent TypeScript type is type XmlJsonArray<T, element extends string> = Record<element, T | T[]>. To implemen ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...

Using TypeScript to ensure the correct typing for the return type of AsyncThunk when utilizing the 'unwrapResult' method from Redux Toolkit

Struggling to determine the appropriate return type for an AsyncThunkAction in order to utilize it with the unwrapResult method from Redux Toolkit (refer to: Redux Tookit: Unwrapping Result Actions): Here is how the Async thunk is declared in the Slice: e ...

The library path in a react (js) integrated mono repo could not be resolved by Nx 16

Greetings everyone, I am a newcomer to the world of NX Monorepo. Following the step-by-step instructions on how to create an Integrated React Monorepo from the official NX website can be found here. I diligently followed each instruction provided. Howeve ...

The function will not be executed when using the v-on:click directive with the b-button

My b-card Dilemma <b-card v-for="todolist in todolists" style='max-width: 20rem;' class='mb-2'> <b-card-title>{{todolist[1].title}}</b-card-title> <b-button href='#' variant='primary' ...

Timeout with Promise

I'm looking to enhance my understanding of working with promises by rewriting this function to resolve the promise instead of resorting to calling the callback function. export const connect = (callback: CallableFunction|void): void => { LOG.d ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Issue: Oops! The digital envelope routines are not supported in Angular while attempting to run the project

I encountered an error when running the command below: ng s The error message is as follows: Error: error:0308010C:digital envelope routines::unsupportedat new Hash (node:internal/crypto/hash:68:19)at Object.createHash (node:crypto:138:10)at BulkUpdateDe ...

"Sorry, there was an issue with AmStockCharts when trying to update the chart: Unable to assign a value to the '

Currently, I am using Angular 4.3.6 along with TypeScript 2.4.2 for my project. The issue that I am facing involves reading data from a socket and attempting to add it to the dataprovider. I came across an example at: While implementing a serial chart, q ...