Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js + Nuxt.js - Why is my computed property undefined when I unit test a head() method?

I have a Vue.js + Nuxt.js component with a head() method:

<script>
    export default {
        name: 'my-page',
        head() {
            return { title: `${this.currentPage}` };
        },
        ...
    }
</script>

currentPage is a computed property.

When I run my application, the component runs correctly and it sets the page title to the right value.

When I run this code from a Jest + Vue Test Utils unit test, the code fails however:

it('should set the title to "my page"', () => {

    const options = {
        computed:{
            currentPage: () => {
                return 'My Title';
            }
        }
    };

    const target = shallowMount(MyPage, options);

    const actual = target.vm.$options.head();

    expect(actual.title).to.equal("My Title");

});

The test fails with the message:

AssertionError: expected undefined to equal 'My Title'

Why is the computed property undefined even though I mock it?

Does the fact that I invoke the head() method through target.vm.$options have anything to do with it?

like image 276
urig Avatar asked Sep 15 '25 05:09

urig


1 Answers

You need to pass context into your head call.

const actual = target.vm.$options.head.call(target.vm);

like image 150
Aldarund Avatar answered Sep 17 '25 20:09

Aldarund