Vuejs单元测试 - 观察者在道具上

时间:2017-08-01 14:12:35

标签: unit-testing vue.js vuejs2 vue-component

我正在尝试在Vue组件中的道具上对观察者进行单元测试。我正在使用Karma + Jasmine。但似乎道具上的观察者不会在单元测试中触发。

这是一个简单的组件:

export default {
    name: 'hello',
    data: function () {
        return {
            b: null
        };
    },
    props: {
        a: {
            type: String,
            default: null
        }
    },
    watch: {
        a(val) {
            this.b = val;
        }
    },
    computed: {
        c() {
            return this.a + " computed";
        }
    }
}

这是我的测试:

describe('Hello', () => {
const HelloCtor = Vue.extend(Hello);
let vm;

beforeEach(() => {
    vm = new HelloCtor({
        propsData: {
            a: "hello"
        }
    }).$mount();
});

afterEach(() => {
    vm.$destroy();
});

it('should watch a and compute c', (done) => {
    vm.$nextTick(() => {
        expect(vm.c).toBe("hello computed");
        expect(vm.b).toBe("hello");
        done();
    });
});
});

在断言中,'c'被正确计算,但'b'始终为空。如果我将'a'移动到数据,一切都很完美。 请注意,当我在浏览器中手动测试我的应用程序时,会触发关于道具的观察者,就像数据变量上的那些一样。

关于如何测试它的任何想法?

1 个答案:

答案 0 :(得分:0)

b始终为空,因为在您开始观察其更改后a未被修改。

当您开始观察变量时,不会触发观察者,只有在其值发生变化时才会触发观察者。