0
votes

I'm trying to unit test a watcher on a props in a Vue component. I'm using Karma+Jasmine. But it seems that watchers on props are not triggered in unit test.

Here is a simple component :

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";
        }
    }
}

and here is my test :

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();
    });
});
});

In the asserts, 'c' is correctly computed but 'b' is always null. If I move 'a' to data everything works perfectly. Note that when I test my app manually in my browser, watchers on props are triggered just like the ones on data variable.

Any ideas on how to test it ?

1

1 Answers

1
votes

b is always null simply because a was not modified after you started watching for its changes.

The watcher is not triggered when you start to watch a variable, it is triggered only when its value changes.