docs icon indicating copy to clipboard operation
docs copied to clipboard

Improve Documentation in Testing

Open LukasBombach opened this issue 4 years ago • 6 comments

What problem does this feature solve?

For a lot of us proper testing is a big topic and it's hard to find documentation on how to test Nuxt-specific features. Currently I am trying to find out how to test asyncData and there is very little information on that on the internet and no information on the website. There is one example on how to run a test with AVA, but I feel testing should be a big part of software development and in the documentation.

What does the proposed changes look like?

Documentation on how to test a Nuxt app, specifically Nuxt-specific features.

This feature request is available on Nuxt community (#c9801)

LukasBombach avatar Sep 20 '19 15:09 LukasBombach

This is quite interesting problem. One way I have worked around this in our codebase is before mounting checking if there is asyncData property and calling that, getting data and applying that to data of component.

Example code:

import Component from "./_.vue";

if (Component.asyncData) {
    const originalData = Component.data();
    const asyncData = await Component.asyncData({
      $axios,
      route,
      params
      redirect
    });
    Component.data = function() {
      return { ...originalData, ...asyncData };
    };
  }

  const component = shallowMount(Component);

The issue though is if you have something that is expecting the data to fail and use redirect + expecting some of the asyncData to be used inside the lifecycle hook like mount you will have some issues :/

Example excerpt of the JS for our specific scenario:

export default {
  name: "TestComponent",
  data() {
    return {
      productDetails: {},
    };
  },
  mounted() {
    this.track();
  },
  methods: {
    track() {
      this.$gtm.trackEvent({
        event: "pageshow",
        taxonomy: {
          id: this.productDetails.id,
          extra: this.productDetails.extra,
        }
      });
    },
  },
  async asyncData({ $axios, route, params, redirect }) {
    try {
      const result = await $axios.get(`/productDetail`);
      return result;
    } catch {
      redirect('/somewhere-else');
    }
  },
};

Trying to test redirect on error with the above workaround will result in errors along the lines of:

Cannot access id of undefined

As mounted will get triggered as soon as I pass component to mount or shallowMount

VladDubrovskis avatar Sep 27 '19 15:09 VladDubrovskis

@VladDubrovskis you helped me a lot with your code example!!! Thank you!

This should be at the documentation! I have spent a lot of time looking for something like this :(

williamweckl avatar Nov 06 '19 01:11 williamweckl

Thanks guys. Also useful: https://gist.github.com/syuji-higa/269b329b6c391fbdc96131b6a44bfcb3

ioandev avatar Jun 04 '20 18:06 ioandev

Thanks for your contributions. We are now closing this repo as docs have now moved to nuxtjs.org using content module. Please continue your contributions on that site especially focusing on the guides folder which is the new docs. Thanks

https://github.com/nuxt/nuxtjs.org/blob/master/README.md

debs-obrien avatar Aug 04 '20 13:08 debs-obrien

suggest some way to do it now stuck here from 2 days can not able to do a unit test for any Axios request I am using nuxt + jest for unit testing, when id testing a page it has Axios call in a method like this
IN pay.vue

async pay(){
   try{
     var respone  = this.$axios.get('API_URL_HERE);
     this.fee = response.data;
   } catch(e){
      console.log(e)
   }
 }

and test file pay.spec.js

import { mount } from '@vue/test-utils';
import paynow from '../pages/pay';
import   axios from "axios";
import Vue from 'vue'

jest.mock("axios", () => ({
  get: () => Promise.resolve({ data: [{ val: 1 }] })
}));
 
describe("paynow.vue", () => {
  it("mocking the axios call to get posts should work", async () => {
    var wrapper = mount(paynow);
    wrapper.vm.pay() 
  });
});

But I am getting this error after running it. TypeError: Cannot read property 'get' of undefined Axios is injected in the plugin then why it is showing undefined

vipulphysiofirst avatar Sep 09 '20 09:09 vipulphysiofirst

jest.mock("axios", () => ({ get: () => Promise.resolve({ data: [{ val: 1 }] }) }));

@vipulphysiofirst You are not mocking axios right. Better way of doing this is:

describe("paynow.vue", () => {
  it("mocking the axios call to get posts should work", async () => {
    var wrapper = mount(paynow, {
         mocks: {
            $axios: {
                get: () => Promise.resolve({ data: [{ val: 1 }] })
            }
         }
    });
    await wrapper.vm.pay() 
  });
});

eduardmavliutov avatar May 20 '21 11:05 eduardmavliutov