Anima-t3d
Anima-t3d

Reputation: 3565

How to set mock nuxt asyncData in jest

I am using Nuxt.js and want to test my page which uses asyncData with Jest. I have a factory function to set up my wrapper, but it basically returns a shallowMount.

Expected

When clicking a button I want the function to behave differently depending on the query parameter. When running the test I want to mock this by setting it directly when creating the wrapper (Similar to setting propsData). E.g. const wrapper = factory({ propsData: { myQueryParam: 'some-value' } });

Result

However trying to set propsData still returns undefined: console.log(wrapper.vm.myQueryParam); // undefined while I would expect it to be 'some-value'

Question

Is there a different approach on how I can test this function that relies on query parameters?

Upvotes: 1

Views: 3720

Answers (1)

ioan
ioan

Reputation: 771

Because asyncData is called before Vue is initialised, it means shallowMount doesn't work right out of the box.

Example:

page:

<template>
    <div>Your template.</div>
</template>

<script>
  export default {
    data() {
      return {}
    },
    async asyncData({
      params,
      error,
      $axios
    }) {
        await $axios.get("something")
    }
  }
</script>

test:

import { shallowMount } from "@vue/test-utils";
describe('NewsletterConfirm', () => {
  const axiosGetMock = jest.fn()
  const axiosPostMock = jest.fn()
  var getInitialised = async function (thumbprint) {
    if (thumbprint == undefined) throw "thumbprint not provided"

    let NewsletterConfirm = require('./_thumbprint').default
    if (!NewsletterConfirm.asyncData) {
      return shallowMount(NewsletterConfirm);
    }

    let originalData = {}
    if (NewsletterConfirm.data != null) {
      originalData = NewsletterConfirm.data()
    }
    const asyncData = await NewsletterConfirm.asyncData({
      params: {
        thumbprint
      },
      error: jest.fn(),
      $axios: {
        get: axiosGetMock,
        post: axiosPostMock
      }
    })
    NewsletterConfirm.data = function () {
      return {
        ...originalData,
        ...asyncData
      }
    }

    return shallowMount(NewsletterConfirm)
  }
  it('calls axios', async () => {
    let result = await getInitialised("thumbprint")
    expect(axiosGetMock).toHaveBeenCalledTimes(1)
  });
});

Credits to VladDubrovskis for his comment: in this nuxt issue

Upvotes: 3

Related Questions