Confirm that a new class has been assigned to an element

I'm having trouble creating a unit test for a Vue.js component where I need to check if a specific CSS class is added to the template.

Below is the template code:

<template>
  <div id="item-list" class="item-list">
    <table id="item-list-lg" class="table table-hover nomargin hidden-xs hidden-sm hidden-md">
      <thead>
        <tr>
          <th>Name</th>
          <th>Included modules</th>
        </tr>
      </thead>
      <tbody>
        <tr v-bind:id="'list-lg-item-' + item.id"
            v-for="item in items"
            v-bind:key="item.id"
            v-bind:class="itemClass(item)">
          <td class="list-item-name">{{item.name}}</td>
          <td class="list-included-parts">
            <span v-for="part in item.parts" :key="part.id">{{part.name}}, </span>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

Here's the Component class (Typescript):

import { Component, Prop, Vue } from 'vue-property-decorator';
import { Item, Items } from '@/models/Item';

@Component
export default class ItemList extends Vue {
    @Prop({required: false}) private items: Item[] = Items;

    public itemClass(item: Item): any {
        return {
            'list-item-details': true,
            'list-global-item': item.isGlobalItem(),
        };
    }
}

The code looks correct as the items are properly highlighted in the component during runtime. However, the unit test fails with the following error message:

Error: [vue-test-utils]: find did not return tr#list-lg-item-id.1, cannot call classes() on empty Wrapper

This is my test code (Typescript):

describe('ItemList.vue', () => {
  const wrapper = shallowMount(ItemList, {
    propsData: { items: Items },
  });

  it('highlights global items in the list', () => {
    Items
      .filter((i) => i.isGlobalItem())
      .map((i) =>
        // For example, list-item-id.1
        expect(wrapper.find(`tr#list-lg-item-${i.id}`).classes())
          .to.contain('list-global-item'));
  });
});

I have tried using find() with just the id instead of a tr element with that id without success. Additionally, when I output the HTML from the wrapper in the test, I can see that the tr element with the correct id is present.

<div data-v-63e8ee02="" id="item-list" class="item-list">
  <table data-v-63e8ee02="" id="item-list-lg" class="table table-hover nomargin hidden-xs hidden-sm hidden-md">
    <thead data-v-63e8ee02="">
      <tr data-v-63e8ee02="">
        <th data-v-63e8ee02="">Name</th>
        <th data-v-63e8ee02="">Included parts</th>
      </tr>
    </thead>
    <tbody data-v-63e8ee02="">
      <tr data-v-63e8ee02="" id="list-item-id.1" class="list-item-details list-global-item">
        <td data-v-63e8ee02="" class="list-item-name">Foo</td>
        <td data-v-63e8ee02="" class="list-included-parts">
          <span data-v-63e8ee02="">Bar, </span>
          <span data-v-63e8ee02="">Baz, </span>
          <span data-v-63e8ee02="">Qux, </span>
          <span data-v-63e8ee02="">Quux, </span>
        </td>
      </tr>
    </tbody>
  </table>
</div>

What could be causing this issue? Could it be related to the fact that the id attribute is set dynamically?

Answer №1

The reason for this issue was due to the id tags containing periods in the generated values, requiring them to be escaped in the selector strings, such as list-item-id\.1.

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

Creating an object type that includes boolean values, ensuring that at least one of them is true

To ensure both AgeDivisions and EventStyles have at least one true value, I need to create a unique type for each. These are the types: type AgeDivisions = { youth: boolean; middleSchool: boolean; highSchool: boolean; college: boolean; open: bo ...

Utilize the v-for Directive in Vue-Tables-2 Templates

I am looking to showcase the data fetched using axios in my dynamically keyed datatables by creating a template. Data Set : "environment": "production", "version": "5.6", "apache_version": "3.2.1" ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

Angular 4's unique feature is the ability to incorporate multiple date pickers without the

Is there a way to implement a multiple date picker using Angular 4 and TypeScript only? I came across one solution but it seems to only support Angular 1. Thank you in advance! ...

Conceal the React button once it has been pressed

In my checklist of questions, I have set up a system where the first button is shown if any checkboxes are selected. If no checkbox is selected, then the second "Submit" button is displayed. Upon clicking submit, a message appears inside. Additionally, for ...

What is the best way to initialize a discriminated union in TypeScript using a given type?

Looking at the discriminated union named MyUnion, the aim is to invoke a function called createMyUnionObject using one of the specified types within MyUnion. Additionally, a suitable value for the value must be provided with the correct type. type MyUnion ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Converting a string to Time format using JavaScript

I am working with a time format of 2h 34m 22s which I need to parse as 02:34:22. Currently, I am achieving this using the following code: const splitterArray = '2h 34m 22s'.split(' '); let h = '00', m = '00', s = &a ...

"Error encountered: Unable to resolve dependency tree" message appears when attempting to run npm install

Encountering dependency errors while trying to execute the npm install command for my Angular application. As a newcomer to TypeScript and Angular, I'm unsure of the next steps to take. Any suggestions? Attempted solutions include clearing the npm ca ...

Highlighting in Coda on MacOS now supports TypeScript

Can anyone help me with getting my Coda editor to properly highlight TypeScript? I checked this page and it says that TypeScript is supported: But in my up-to-date version of Coda, the list of supported languages seems different. Is there a way to make Ty ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

Atom-typescript does not always successfully compile all typescript files to JavaScript

Currently, I am in the process of learning how to implement routing in Angular2 by following a tutorial. The tutorial involves creating partial pages using .ts files along with companion .js files for each page. While my Atom editor, equipped with atom-typ ...

Setting compilerOptions.isCustomElement for VueJS 3 in a Laravel project: A step-by-step guide

I am currently working on integrating VueJS 3 into a Laravel project and utilizing a JS file to implement a markdown toolbar. The JS file contains functions that generate buttons for applying various markdown options. Everything is functioning properly, bu ...

When utilizing Typescript to develop a form, it is essential to ensure that the operand of a 'delete' operator is optional, as indicated by error code ts(279

Can someone help me understand why I am encountering this error? I am currently working on a form for users to submit their email address. export const register = createAsyncThunk< User, RegisterProps, { rejectValue: ValidationErrors; } > ...

What is the best way to store tests away from the source directory in Vite projects?

Executing npm init vue@latest using the specified setup https://i.stack.imgur.com/2c7XX.png results in a Vitest spec file being created in the src directory. I am curious as to why Cypress e2e tests are placed in a separate directory while Vitest unit te ...

Developing a declaration for an unnamed function in a JavaScript file

module.exports = function (argument1, argument2) { return { myFunction } function myFunction () { ... } } What is the process for creating a TypeScript declaration file for this specific JavaScript file? ...

Unable to retrieve device UUID using capacitor/device on Android

I'm currently attempting to obtain the UUID of my devices so that I can send targeted notifications via Firebase. My front end and back end are connected, enabling the back end to send notifications to the front end using Firebase. However, all I am a ...

The function call with Ajax failed due to an error: TypeError - this.X is not a function

I am encountering an issue when trying to invoke the successLogin() function from within an Ajax code block using Typescript in an Ionic v3 project. The error message "this.successLogin() is not a function" keeps popping up. Can anyone provide guidance on ...

What is the best way to transfer the variant property of the material-ui TextField when using a higher-level React component?

I'm encountering difficulties with typing... Essentially, I have a wrapper React component for the @material-ui TextField but I am struggling with getting the typings correct for the variant property. Here's the main problem. Using @material-ui ...

What is the best way to ensure that GCM push notifications are still received even when the app is closed or the

Currently, I'm in the process of developing an application using Ionic 2 that requires push notifications to be received. In certain scenarios, such as when the app is force-stopped on Android or when the device is turned off, push notifications are ...