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

How can I modify the color in vue-google-chart when a filter option is selected?

I created a stack column chart with a filter that changes the color to blue when selected. Here is my Vue app: https://codesandbox.io/s/vue-dashboard-chart-6lvx4?file=/src/components/Dashboard.vue I expected the selected color to match the color in the ...

Pug does not have access to computed properties within the dynamic class attribute of a Vue component

After attempting to dynamically toggle the className based on computed property and encountering issues in Pug, I found that manually setting 'true' to a className was the solution. Even after trying to reassign the computed property to a Pug var ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

V-model prevents checkbox from being checked upon clicking

codesandbox: https://codesandbox.io/s/github/Tapialj/AimJavaUnit6?file=/src/frontend/src/components/AddMovieForm.vue I am currently working on implementing a feature where I need to collect an array of selected actors using checkboxes. I have set up a v-m ...

Having trouble importing or resolving files with ts-loader or css-loader?

Struggling to incorporate css modules by utilizing style-loader and css-loader in my project. I am facing difficulties understanding the root cause, unsure if it's ts-loader or css-loader to blame. webpack.config.js const path = require('path&a ...

Apexcharts - Blank space in area chart

I am currently facing an issue while trying to create an area chart using apexcharts on nuxt (vue2). The problem is that the area is not being filled as expected, and the options I have set in chartOptions for fill are affecting the line itself instead of ...

``Incorporating Vue.js: A Guide to Emphasizing the Chosen Selection from Numerous Lists

I am currently utilizing Vue.js and have multiple lists displayed, but I only wish to select and highlight one element at a time. Currently, every click results in multiple items being highlighted. I hope that explanation is clear. Below are the snippets o ...

VueJs: utilizing computed properties within a looped property

Uncertainty clouds my judgment on whether the question title is the optimal approach for achieving my goal. To elaborate on the issue at hand: Within a Vue root component, I have a property specified within the data key, such as months. As I iterate over ...

Steps for personalizing the dataset on a PrimeNG bar graph

I'm currently working with primeng in an Angular project and I need to create a bar chart where the last two horizontal bars have different colors. Right now, the last two bars are incorrectly being assigned to represent dogs and cats. My goal is to ...

`Angular 9 template directives`

I am facing an issue with my Angular template that includes a ng-template. I have attempted to insert an embedded view using ngTemplateOutlet, but I keep encountering the following error: core.js:4061 ERROR Error: ExpressionChangedAfterItHasBeenCheckedEr ...

Setting up Typescript for a Node.js project configuration

I am facing an issue with my simple class class Blob { } After compiling it with TypeScript, I encountered the following error message: ../../../usr/lib/node_modules/typescript/lib/lib.dom.d.ts:2537:11 2537 interface Blob { ~~~~ ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

What is the correct way to wrap an http.get in TypeScript?

My understanding of Typescript is limited, so I have a basic question related to my web application's frontend. In most http get-requests, I need to include two parameters. To simplify this process, I created a simple wrapper for HttpClient (from "ang ...

Troubleshooting error messages with Angular Mock Inject in Karma and Jasmine

While attempting to perform unit tests on an Angular (Ionic) 1 application, utilizing the angular.mock.inject(...) function triggers a mysterious error. What's perplexing is that there is no specific error message provided, which hinders the debugging ...

Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects ...

What is the best way to showcase the following values using Vue.js?

{"status":true,"data":[{"ref_id":"22","agent_id":"68","p_id":"84","description":"i am interested"},{"ref_id":"24","agent_id":"68","p_id":"84","description":"For more information about Bootstrap and Bootstrap Glyphicons, visit our Bootstrap Tutorial.For mor ...

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

Data can be retrieved in a React/Next.js application when a button is clicked, even if the button is located in a separate

Whenever the button is clicked, my function fetches weather data for the current location. I am trying to figure out how to transfer this data from the Location component to the pages/index.tsx. This is where another component will display the data. This ...

The formBuilder validator pattern seems to be malfunctioning

I am attempting to display a message when the password does not meet the formGroup pattern. Here is how my FormGroup is initialized: this.signupForm = fb.group({ userName: ['', Validators.compose([Validators.required,Validators.pattern(/^&bsol ...