Vue-test-utils + CSS modules: wrapper.classes() returns empty array
Asked Answered
N

2

6

I'm fairly new to Vue Test Utils and CSS Modules. I've got my Vue component set up using CSS Modules and everything works fine in the app and my Storybook. For example my BasicButton:

<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>

Before I switched to CSS Modules my Jest tests ran great. But now the following test results in an error:

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

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

The error thrown is:

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 can't seem to find any solution, so perhaps somewhere here can help me get going?

Nelsonnema answered 10/9, 2020 at 17:34 Comment(1)
I can't reproduce the problem. Can you share a link to a reproduction?Farmhouse
S
0

Try:

expect(wrapper.classes()).find('baseButton--large')).toBe(true)
Servitor answered 8/8, 2021 at 18:39 Comment(0)
S
0

I think you can solve it by using wrapper.vm.$style, so you can get the generated CSS classes and use it to your tests.

In my tests I'm using something like this:

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

import MyComponent from './MyComponent.vue'

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

    expect(titleElement.exists()).toBe(true)
    expect(titleElement.text()).toBe(title)
    expect(bodyElement.exists()).toBe(true)
    expect(bodyElement.text()).toBe(body)
  })
})

Shepherd answered 23/2, 2023 at 3:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.