【问题标题】:How to test style css custom var in VueJS如何在 VueJS 中测试样式 css 自定义 var
【发布时间】:2021-03-11 18:41:44
【问题描述】:

我正在 VUEJS 中创建一个测试,我想获得样式。 我的组件是这样使用的:

:style="background-color: var(--color)"

我正在使用以下方法:

  1. wrapper.find('.avatar').attributes().style
  2. wrapper.find('.avatar').element.style.getPropertyValue('background-color')

如何在我的测试中模拟 var(--color) 自定义变量?

【问题讨论】:

    标签: vue.js unit-testing jestjs


    【解决方案1】:

    为了测试这一点,我们需要一种在父元素中指定 CSS 变量的方法,将变量传播给它的子元素。不幸的是,Jest 使用 JSDOM,它不完全支持 CSS 变量。它有一个partial implementation,它只将 CSS 变量应用于单个元素,而不将其级联到子元素。

    但是,如果 JSDOM 曾经添加对 CSS 变量的支持,测试将如下所示:

    1. 创建一个 HTML 元素(例如,命名为“testEl”),我们可以在其中设置 CSS 属性。
    2. 在带有testEl.style.setProperty() 的元素上设置--color 属性。
    3. 使用 Vue Test Utils 的 attachTo mounting option 将测试组件安装到上面创建的元素上。
    4. 在 wrapper 元素上使用 window.getComputedStyle() 以获取从 CSS 变量计算的样式,并使用 getPropertyValue() 获取 background-color 的计算值,该值应等于步骤 2 中设置的值(即 blue) .

    示例(理论):

    describe('MyComponent.vue', () => {
      it('receives --color', async () => {
        const testDiv = document.createElement('div')
        testDiv.style.setProperty('--color', 'blue')
    
        const wrapper = shallowMount(MyComponent, {
          attachTo: testDiv
        })
    
        // ⛔️this will fail because JSDOM doesn't fully support CSS variables
        expect(getComputedStyle(wrapper.element).getPropertyValue('background-color')).toBe('blue')
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 2020-05-27
      • 1970-01-01
      • 2022-01-26
      • 2017-12-23
      相关资源
      最近更新 更多