Testing Vue components with Typescript and Jest does not display the expected values in the HTML output

Recently, I decided to focus on Test-Driven Development (TDD) using Typescript, so I started a new Vue project with vue-cli. I specifically chose Vue3, Typescript, and Jest for this project. However, when I ran the unit test initially, it failed to execute successfully. After looking into it further, I discovered that the mount command from @vue/test-utils was not rendering any of the prop values as expected:

In my HelloWorld.vue file:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    {{ test }}
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";

@Options({
  props: {
    msg: String,
  }
})
export default class HelloWorld extends Vue {
  msg!: string;
  test: string = "It's a test";
}
</script>

Here is an excerpt from example.specs.ts file:

import { mount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("renders props.msg when passed", async () => {
    const msg = "new message";
    const wrapper = mount(HelloWorld, {
      props: { msg }
    });
    
    expect(wrapper.text()).toContain(msg);
  });
});

Upon printing wrapper.html(), the output showed:

<div class="hello" msg="new message"><h1></h1></div>

Surprisingly, the msg or test values were not being rendered in the HTML content. While these attributes were specified as props, they did not appear in the final rendering on the page.

I suspect that one possible cause could be the usage of a Typescript component instead of a more traditional one, which might be causing some confusion within the rendering process. At this point, I'm unsure about the exact solution. Any suggestions or advice would be greatly appreciated!

Answer №1

After thorough investigation, it was discovered that the issue stemmed from vue-jest. Luckily, a solution has been implemented. Check out the details here: https://github.com/vuejs/vue-jest/pull/299

Answer №2

  1. Your Greetings component is not recognized as a component, here's how you should define it:

    @Component
    export default class Greetings extends Vue {
      @Prop() message!: string;
    

@Component informs the compiler that it is a component.

@Prop() indicates to the compiler that the message property is a prop.

  1. Utilize propsData as mount options or use setProps documentation link:

    const wrapper = mount(Greetings, {
      propsData: {
        msg, // or msg: msg, 
      },
    });
    

Outcome:

  console.log tests/unit/example.spec.ts:13
    <div class="hello">
      <h1>
        new message
      </h1>
      It's a test
    </div>

Answer №3

Although the initial solution didn't completely resolve the issue, I have decided to explore an alternative approach by opting for functional components with TypeScript integration instead of using class-based components.

Here is an example from a file named HelloWorld.vue:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    {{ test }}
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: String
  },
  data() {
    return {
      test: "It's a test" as string
    }
  }
});
</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

Stop Node Modules from Referencing Global Location

Recently, I ran into an issue after updating my project from Git. The problem arose when trying to use ngx-material-timepicker in conjunction with the luxon library. (It's important to note that ngx-material-timepicker isn't a new addition to th ...

Having trouble sending posts to an API route with Angular's HTTP module

When attempting to send values via a POST request in the URL of an Angular5 Laravel API route, I encountered an issue. Despite not receiving any errors in the browser console, no network activity was recorded upon sending the request. It is perplexing as I ...

Having trouble generating a Vue project using vue/cli?

I am currently developing a vuex application using Vue CLI. Unfortunately, the CLI gets stuck during metadata fetching (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb88838480828f8a99abd9c5dac5dd">[email protected]</a& ...

vee-validate - Standalone form validation with distinct procedures

I currently have a situation where I am dealing with two forms, each in separate steps and having their own submit button. Using $validator.validateAll() validates all the inputs on the page, but I specifically need validation for each form individually. ...

Error in TypeScript React: "Could not locate module: Unable to locate 'styled-components'"

Even though I have installed the @types/styled-components package and compiled my Typescript React app, I am consistently encountering this error: Module not found: Can't resolve 'styled-components' I have double-checked that 'style ...

Utilizing Vue.js components and properties to invoke a function

Trying to create a shopping cart button that keeps track of how many times it's clicked, but encountering an issue where the function called by the button doesn't receive the correct parameter. I attempted using {{id}} and :onClick="addThisToCar ...

Is it possible to retrieve data from a promise using the `use` hook within a context?

Scenario In my application, I have a component called UserContext which handles the authentication process. This is how the code for UserProvider looks: const UserProvider = ({ children }: { children: React.ReactNode }) => { const [user, setUser] = ...

Only load the value in ref when it is specifically requested in Vue

Within my Vue project, I am utilizing a ref variable that stores data retrieved from a database. This reference is contained within Pinia's setup store for easy access. The objective is to load the data only when requested by the user and then always ...

Aurelia: The passing down of views and view-models

In the process of developing an Aurelia app, I am tasked with creating functionality that allows users to display various lists for different resources. These lists share common features such as a toolbar with search and refresh capabilities, along with a ...

[Vue warning]: The property "text" was accessed during rendering, however it is not defined on the current instance using Pug

Looking for some guidance from the Vue experts out there. I've recently started working with Vue and I'm attempting to create a view that verifies an email with a unique code after a user signs up. Right now, my view is set up but it's not c ...

Angular 2 is throwing an error: Unhandled Promise rejection because it cannot find a provider for AuthService. This error is occurring

My application utilizes an AuthService and an AuthGuard to manage user authentication and route guarding. The AuthService is used in both the AuthGuard and a LoginComponent, while the AuthGuard guards routes using CanActivate. However, upon running the app ...

How can I fetch and reference multiple local JSON files in Vue using Axios?

I am currently utilizing vue for prototyping some HTML components. Is there a method to make Vue detect two separate JSON files? vue.js var vm = new Vue({ el: '#douglas-laing', data: { products: [], contentPanels: [] }, created() ...

Accessing arrays using bracket notation

When working with TypeScript (or JavaScript), you have the option to access object properties using either dot notation or bracket notation: object.property object['property'] Let's explore a scenario using the latter method: const user = ...

Error TS2694 is being caused by Electron Typescript Material-UI withStyles because the namespace "".../node_modules/csstype/index"" does not have an exported member called 'FontFace'

While I am experienced with Material-UI, I am relatively new to Electron and using React, TypeScript, and Material-UI together. Recently, I encountered an error while attempting to create an electron boilerplate code for future project initialization. Init ...

What could be causing the inner array typescript to be inaccessible in an Angular 5 application?

Below are the JSON definitions that I am working with: export class Company { name: string; trips : Trip[] = []; } export class Trip{ id: number; name: string; } Within the component, there is a method that contains the ...

Exploring Angular and Typescript - attempting to adjust cursor position for multiple child elements within a contenteditable div despite researching numerous articles on the topic

I could use some assistance in resolving this issue. Here is the stackblitz code I am currently working with If you have any workarounds, please share them with me. The caret/cursor keeps moving to the starting position and types backward. Can anyone hel ...

The 'type' property is not present in the 'ChartComponent' type, however, it is necessary in the 'ApexChart' type

Encountered an error highlighted in the title: Property 'type' is missing in type 'ChartComponent' but required in type 'ApexChart'. Any attempt to resolve this issue led to another error message: Type '{ type: string; ...

My form submission is getting messed up by VueJS, causing it to delete all of the data

It seems that VueJS is causing issues with my form submission process, as it is removing the post data from the Ajax serialize() function. I suspect it could be due to the combination of using Ajax and Jquery, but I'm unsure how to resolve this issue ...

Angular: How to Resolve Validation Error Messages

I have a TypeScript code block: dataxForm: fromGroup this.dataxForm = new FormGroup({ 'Description':new FormControl(null, Validaros.required}; 'Name':new FormControl(null, Validators.required}) Here is an HTML snippet: <mat-divider& ...

Combining two elements in Angular 2

I am looking to find the intersection of two objects. My goal is to compare these objects and if they have matching values on corresponding keys, then I want to add them to a new object. obj1 = { "Projects": [ "test" ], "Companies": [ "facebook", "google ...