如何通过道具测试零件?

时间:2019-10-26 13:31:09

标签: unit-testing vue.js jestjs

我正在学习Vue中的单元测试,并尝试根据本文https://alligator.io/vuejs/testing-vue-with-jest/

来测试组件

我有一个组件

<template>
    <div>
        <h1 :style="headingStyles">{{title}}</h1>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                headingStyles: {
                    color: this.color
                }
            };
        },
        props: ["title", "color"]
    };
</script>

和包含测试用例的文件

import Vue from 'vue';
import FancyHeading from '../../src/components/FancyHeading';

function mountComponentWithProps (Component, propsData) {
    console.log('props Data', propsData)
    const Constructor = Vue.extend(Component);
    const vm = new Constructor({
        propsData
    }).$mount();

    return vm.$el;
}

describe('FancyHeading.vue', () => {
    it('should be the correct color', () => {
        const headingData = mountComponentWithProps(FancyHeading, { color: 'blue' });
        const styleData = headingData.style.getPropertyValue('color');
        console.log(styleData)
        expect(styleData).toEqual('blue');
    });

    it('should have the correct title', () => {
        const headingData = mountComponentWithProps(FancyHeading, { title: 'Hello, Vue!' });
        const titleData = headingData.textContent;

        expect(titleData).toEqual('Hello, Vue!');
    });
});

运行yarn test:unit时收到错误消息

FancyHeading.vue › should be the correct color

    expect(received).toEqual(expected) // deep equality

    Expected: "blue"
    Received: ""

看起来颜色是空的xtring,但我不明白为什么。有人可以解释我并帮助通过考试吗?

0 个答案:

没有答案