1

I'm using jest / vue-test-utils to test a component, and I can't find a way to set props if they are used in mounted().

The component has one prop queryFilter: { type: Object } which is used within the mounted() hook.

My test looks like this:

import { mount } from '@vue/test-utils'
import Filter from '../../src/components/Filter.vue'
test('basic fail', async () => {
     const filter = mount(Filter);   
     await Filter.setProps({
        propsData: { queryFilter: { "foo": "bar" } }
    });
    expect(filter.vm.queryFilter).toEqual({ "foo": "bar" });
});

The error I get suggests that I tried to mount, triggering the mounted() hook, but props were not yet passed because setProps is called in the next line.

 TypeError: Cannot convert undefined or null to object
        at Function.keys (<anonymous>)
    > 75 |       let tables = Object.keys(this.queryFilter);

Of course, if I swap the two lines

     await Filter.setProps({
        propsData: { queryFilter: { "foo": "bar" } }
    });
    const filter = mount(Filter);   

then I get TypeError: _Filter.default.setProps is not a function. Obviously.

Is there any way to use vue test in this case?

1 Answer 1

1

You could directly pass the props when mounting your component.

Example:

import { mount } from '@vue/test-utils'
import Filter from '../../src/components/Filter.vue'

test('basic fail', async () => {
    const filter = mount(Filter, {
        props: {
            queryFilter: { "foo": "bar" }
        }
    });   
    expect(filter.vm.queryFilter).toEqual({ "foo": "bar" });
});

For further details check out the docs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.