Empty array returned when using wrapper.classes() with Vue-test-utils and CSS modules

Recently I started using Vue Test Utils along with CSS Modules. My Vue component is all set up with CSS Modules and it functions perfectly in the app as well as in Storybook. Take my BasicButton for example:

<template>
  <button
    :class="[
      $style.baseButton,
      $style[`baseButton--${type.toLowerCase()}`],
      $style[`baseButton--${size.toLowerCase()}`],
    ]"
    v-on="$listeners"
  >
    <slot />
  </button>
</template>

<style lang="scss" module>
@import 'src/design/index.scss';

.baseButton {
...
}
</style>

Prior to switching to CSS Modules, my Jest tests were running smoothly. However, after the switch, a particular test is throwing an error:

it('should set a Large size', () => {
    const wrapper = mount(BaseButton, {
      propsData: {
        size: Size.Large,
      },
    });

    expect(wrapper.classes()).toContain('baseButton--large');
  });

The error message reads:

expect(received).toContain(expected) // indexOf

    Expected value: "baseButton--large"
    Received array: []

      25 |     console.log(wrapper);
      26 | 
    > 27 |     expect(wrapper.classes()).toContain('baseButton--large');
         |                               ^
      28 |   });
      29 | 
      30 |   it('should set a Primary state', () => {

      at Object.<anonymous> (src/components/_base-button.component.spec.ts:27:31)

I've tried looking for a solution but haven't had any luck. Any help or advice on how to move forward would be greatly appreciated.

Answer №1

Attempt:

verify(wrapper.classes()).lookFor('baseButton--large')).toEqual(true)

Answer №2

One possible solution is to utilize wrapper.vm.$style in order to access the CSS classes generated and incorporate them into your test cases.

In my testing scenarios, I typically implement a similar approach:

import { mount } from '@vue/test-utils'

import MyComponent from './MyComponent.vue'

describe('MyComponent', () => {
  it('displays a title and content', () => {
    const title = 'Lorem ipsum'
    const content = 'Lorem ipsum dolor sit amet.'
    const wrapper = mount(MyComponent, {
      propsData: {
        title,
        content
      }
    })
    const style = wrapper.vm.$style
    const titleElement = wrapper.find('.' + style['my-component-title'])
    const contentElement = wrapper.find('.' + style['my-component-content'])

    expect(titleElement.exists()).toBe(true)
    expect(titleElement.text()).toBe(title)
    expect(contentElement.exists()).toBe(true)
    expect(contentElement.text()).toBe(content)
  })
})

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

Customize Bootstrap 5: Changing the default color scheme

Currently, I am utilizing Bootstrap 5 (v5.2.1) along with a form on my website. I am attempting to customize the default styles for form validation. Specifically, I want to modify the colored 'tick' or 'check' icon that is displayed wh ...

Creating a Vertical Stack of Divs Using HTML and CSS

I've attempted various methods to align the links vertically in the left-most column, but without success. Any suggestions or advice would be greatly appreciated! http://jsfiddle.net/adRuz/112/ .box { background: #E8E8E8; border-radius: 8px ...

Horizontal Accordion Design for Cascading Style Sheets (CSS) Books

I am currently working on developing a page that features a book layout. This page will include tabs that users can expand individually. If you would like to see a working example, you can check out this link: https://codesandbox.io/s/book-layout-l28gh?fi ...

Incorporating a stationary navigation bar alongside a parallax scrolling layout

After spending the entire night trying to figure this out, I have had zero success so far. I decided to tackle this issue with javascript since my attempts with CSS have been completely fruitless. This is a demonstration of the parallax scrolling webpage. ...

The issue of Ejs partial header and footer file only functioning in one file and not the other (both at the same directory level)

I'm in the process of setting up a view page for a post on the main page of a website. Both pages share the same header and footer files, located at the same directory level. However, while one page is functioning correctly, the other is not. The erro ...

What is the best way to choose the initial and final <td> that appears within a <tr>?

I am working with an html table that has the following structure: <table> <tbody> <tr> <input type="hidden" name="a" value="x"> <input type="hidden" name="b" value="y"> <td>First Ce ...

Can you show me how to create a React Testing Library test that verifies how hovering changes the style of components?

I am currently testing my application and came across a peculiar issue. As I was attempting to test whether a row in my dropdown component triggers an effect on hover, I noticed that I was unable to verify elements based on their background color. Even wh ...

Vue.Js allows developers to easily set a default selected value in a select dropdown menu

Having trouble with getting the default selected value using select in VueJs. I've attempted two different approaches: Using id and v-model fields in the select like this: <select v-model="sort_brand" id="sort-brand" class="form-control"> ...

Using the Google Identity Services JavaScript SDK in conjunction with Vue and TypeScript: A comprehensive guide

I am currently working on authorizing Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript application. Following the guidelines provided here, I have included the Google 3P Authorization JavaScript Library in ...

Blazor: Personalizing color variables in _root.scss - A Step-by-Step Guide

Upon inspecting the generated project, I noticed a multitude of color variables such as --bs-body-bg. The developer tools indicate it is in _root.scss, however, that file appears to be non-existent and I suspect those variables may actually reside within b ...

Exploring unique v-ifs in Vue.js based on a prior selection

I'm having trouble showing different divs based on select options. Even though I have set up v-if conditions for both "de" and "fr", only the first one is being displayed when "fr" is selected. Any idea what's causing this issue? I can't se ...

Error: Unable to set value on Vuejs key - the target is read-only

Currently, I am utilizing a combination of Laravel9 with Vuejs3. In one of my blade views, I pass PHP variables to a Vue component like so: <subscription-form location="{{ $props['location'] }}" orientation="{{ $props['ori ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

An image that is in motion at an inappropriate time

My website has run into an issue. Within the navigation bar, there are two unordered lists containing list items and nested ul tags with images in some of the list items. When applying animations, the image moves along with the tabs. Here are visual exampl ...

What causes the Material-UI Grid element to shift upon clicking it?

I have encountered an issue while developing a React app with Material UI. The problem arises on a specific page of the application. This particular page consists of text and a button aligned vertically, along with a second set of text and another button ...

Why does my MEVN application only display the back end when I try to deploy it on Heroku?

I am encountering an issue with my app deployment on Heroku where the backend server is being displayed instead of my Vue app. Despite having an if statement in app.js that serves the files only in production, removing the if statement did not resolve the ...

Utilizing Vue Cli 3 to Implement Service Worker Registration with Firebase

After using Vue-cli 3 to create a Vue app, I attempted to integrate FCM into it but have been struggling for two days with no success. Below is the code snippet I've been working with: importScripts('https://www.gstatic.com/firebasejs/4.8.1/fir ...

What steps should I take in modifying my existing code to use jQuery to set my div to a minimum height rather than a fixed height?

Could someone assist me in adjusting my div to have a min-height instead of a regular height? Whenever I click on the "Learn more" button, it extends past my div because the function is designed to set a specific height rather than an equal height. $.fn.e ...

Easily center list item numbers vertically within fixed height containers

I am facing an issue with the alignment of ordered list item numbers in a list with fixed height and vertically centered content. The numbers seem to be positioned inaccurately. li { height: 80px; border: 1px solid black; } li > span { heigh ...

Tips for loading a webpage with optimal speed and efficiency

I am inspired by the sleek design of Apple's website and want to replicate some of its features in my project (best viewed on FF, Chrome, Safari): Initially, the page appears empty except for the header - but the final height of the page is already ...