Error message encountered when using Vue and typescript: "TypeError: Object prototype may only be an Object or null: undefined"

Encountered a TypeError: Object prototype may only be an Object or null: undefined

I ran into an issue while working on my project. I'm utilizing vuejs, typescript, and jest.

Despite having simple code, I encountered an error when trying to unit test with jest. Below is the snippet of my test code:

///<reference path="../../../../node_modules/@types/jest/index.d.ts"/>
// https://vue-test-utils.vuejs.org/kr/s
import { mount } from "vue-test-utils";
import HelloWorld from './HelloWorld.vue';

describe('[HelloWorld]', function () {
  let cmp: any;

  beforeEach(() => {
    cmp = mount(HelloWorld);
  });

  it("Check vue instance", () => {
    expect(cmp.isVueInstance()).toBeTruthy();
  });

  it("message is Hello", () => {
    expect(cmp.vm.msg).toEqual('Hello!!');
  });
});

And here is the content of the vue file:

   <template>
   <div class="hello">
       <h1>{{ msg }}</h1>
       <img src="/assets/logo.png">
       <button @click="clickHandler">
         button
       </button>
     </div>
   </template>

   <script lang="ts">
   import Vue from "vue";
   import Component from "vue-class-component";

   interface HelloWorldInterface {
     msg: string;
     clickHandler(): void;
   }

   @Component({})
   export default class HelloWorld extends Vue implements HelloWorldInterface {
     msg = "Hello!!";
     clickHandler() {
       window.alert(this.msg);
     }
   }
   </script>

For details and a visual representation of the error logs, click here.

Answer №1

To enable compatibility with Jest, ensure that the esModuleInterop option is set to true in your tsconfig.json or a custom tsconfig.

Answer №2

Vue2's exposure method appears to be the root cause of the issue, leading to an error when using import Vue from "vue".

To resolve this, I implemented 'vue-property-decorator' in the following way:

import { Vue, Component, Prop } from 'vue-property-decorator';

But what exactly does 'vue-property-decorator' accomplish? It imports Vue and then exports it as a named export rather than a default one. This technique could potentially be applied in your own code too.

import Vue, { PropOptions, WatchOptions } from 'vue';
...
export { Component, Vue, mixins as Mixins };

Answer №3

In my experience, replacing import Vue from "vue" with

import * as Vue from "vue"
resolved the issue in projects with a similar setup. Here is an example:

//import Vue from "vue";
import * as Vue from "vue";
import Component from "vue-class-component";

interface HelloInterface {
  message: string;
  handleClick(): void;
}

@Component
export default class Hello extends Vue implements HelloInterface {
  message = "Hey there!!";
  handleClick() {
    window.alert(this.message);
  }
}

Although it may be more complex, it does get the job done. I have created a demo using vue-cli for reference: https://codesandbox.io/s/mjvjw2xw39

Answer №4

Do not

 describe("Verify message says Hello", () => {
    expect(component.vm.message).toEqual('Hello World!');
  });

Instead, consider using

describe("Check if message displays Hello", () => {
    expect(component.message).toEqual('Hello World!');
  });

Answer №5

The issue was resolved when I deleted the "lang='ts'" attribute from the tag.

Answer №6

Take a look at this helpful link that guided me through resolving a CIRCULAR DEPENDENCY problem using the command

npx madge --circular --extensions ts ./

Link: To Identify Circular Dependency in your package

However, I'm still encountering the same Error..!! :(

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 significance of zone.js and rxjs within the context of Angular 2

As a newcomer to Angular2, I recently learned about zone.js and rxjs. I'm curious to know if they both serve the same purpose for handling asynchronous tasks, or if each has its own specific role. Can someone explain to me the exact reasons why zone.j ...

Problems with Vue components functioning on a live server

After deploying my project on a live server, I encountered a problem where my components are not being rendered. Everything works properly on my local machine after running npm run production, but when I upload the changes to the live server, none of the V ...

Having trouble activating the Samsung Tizen TV through the designated APIs

I currently have a Tizen Application for managing TV Operations such as Volume Controls and Power On/Off. I have implemented the use of b2bapis for Power Off functionalities, but I am struggling to locate comprehensive documentation on the same. The code s ...

"Incorporating an onChange event handler to an input field in a React

I'm currently facing a challenge with my input box component as I aim to implement a script that will restrict all inputs except for numbers. function onChangeHandler(e: React.ChangeEvent) { this.value.replace(/(?![0-9])./gmi,''); } expo ...

The title attribute in Vue3 is updated through props, but computed properties remain unaffected

I incorporated an external library into my project using Vue3. The component I am utilizing is sourced from a third-party library [Edit: Upon realizing that the GitHub repository for this library is no longer being maintained, I have updated the code to re ...

How can I prevent buttons from interfering with an onPaste event?

I've created an image modal that allows users to upload or paste an image. Everything is working well, except for the fact that the buttons on the modal are capturing the focus. This means that pasting only works if the user manually clicks outside th ...

What is the process of converting Luxon DateTime format into a string or numerical representation?

After setting up a Luxon clock for my project, I am facing an issue while using a component to define the month number of the current date. import { DateTime } from 'luxon'; import React, { useEffect, useState } from 'react'; interface ...

The attribute 'listen' is not a valid property for the data type 'NavigateFunction'

Just diving into the world of Typescript and react, I recently made the switch from useHistory to useNavigate in react-router-dom v6. However, when using the navigate.listen(e) method inside the useEffect hook, I am encountering the error "Property ' ...

Ways to invoke a slice reducer from a library rather than a React component

I've been working on a React application using the React Boilerplate CRA Template as my foundation. This boilerplate utilizes Redux with slices, which is great for updating state within a React component. However, I'm facing a challenge when try ...

I am having trouble importing and using a Vue.js single-file component after the project has been built

I've been exploring ways to reuse some of my components from one repository in another repository. One of the components I'm working with is a single file component. To achieve this, I set up webpack to generate a .js bundle for that particular c ...

Angular 14 introduces a new feature that automatically joins open SVG paths when dynamically rendered from a data object

I developed an application to convert SVG code into a JSON object that can be stored in a database. Another app was created to dynamically display the rendered result on a webpage. The rendering output appears as shown in this image: https://i.sstatic.net/ ...

What is the reason behind using `Partial<>` to enclose the Vue props?

I am currently working with a combination of technologies, and I am struggling to pinpoint the root cause of the issue. Here is the Tech Stack: Vue 3 TypeScript Vite VSCode / Volar unplugin-vue-macros (https://github.com/sxzz/vue-macros) unplugin-vue-com ...

Alerts appear immediately upon beginning to type, asking for 8 characters and ensuring both passwords match

Is it possible to notify users that both passwords should match and they need to enter at least 8 characters after typing? There is currently an issue where a notification appears for entering less than 8 characters, but the password reset still proceeds ...

Retrieving attributes by their names using dots in HTML

Currently working on an Angular 2 website, I am faced with the challenge of displaying data from an object retrieved from the backend. The structure of the object is as follows: { version: 3.0.0, gauges:{ jvm.memory.total.used:{ value: 3546546 }}} The is ...

Need help fixing the npm run watch error in Laravel/Vue?

While attempting to execute an npm run watch command in the console, I encountered a specific error message. Here is the error that was displayed × Mix Compiled with some errors in 50.24ms ERROR in ./resources/js/app.js 9:0-28 Module not found: Error: C ...

Refreshing an Angular page when navigating to a child route

I implemented lazy loading of modules in the following way: { path: 'main', data: {title: ' - '}, component: LandingComponent, resolve: { images: RouteResolverService }, children: [ { path: '', redirectTo: 'home&apo ...

Getting headers from an HTTP response in VueJS is a common task that many developers encounter

I am utilizing axios to fetch data from the backend. After sending a request, I receive a response; however, I am struggling to read some of my headers. The headers that I need to access are 'content-type', 'content-length', 'x-wp- ...

Tips for utilizing the eventHub feature in Nuxt

Looking to utilize the eventHub on Nuxt.js? Traditionally, we would set up the eventHub in the main.js file like so: export default { name: "App", data() { return { eventHub: new Vue() }; }, provide() { return { e ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...

Executing a Javascript function through Typescript in an Ionic application

I integrated a plugin into my ionic project, which includes both Java and JS code: cordova.define("cordova-sms-plugin.Sms", function(require, exports, module) { 'use strict'; var exec = require('cordova/exec'); var sms = {}; functio ...