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?
You need to pass context into your head call.
const actual = target.vm.$options.head.call(target.vm);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With