Summer Sale! All accounts are 50% off this week.

pookerbutt's avatar

Getting started with Jest on Vue/Laravel project

I'm just starting to learn Jest and I'm having some issues getting started. Basically I'm trying to test a function that fetches data when the component mounts. From my understanding the best option is to make a mock version of the axios request.

So I made one like so -

jest.mock("axios", () => ({
  get: () => Promise.resolve({ card: {info: {title: "this is the title"}}})
}));

However, when I try to run the test I get this error -

UnhandledPromiseRejectionWarning: ReferenceError: axios is not defined
(node:35060) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:35060) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. 

Any Ideas why it does not recognize the mocked axios function?

Here is the full test file

import {createLocalVue, mount, shallowMount } from '@vue/test-utils';
import CardBilledBeforeSigned from '@/components/metrics/datacards/CardBilledBeforeSigned.vue';
import routeMixin from "../../../../../resources/js/mixins/routes/RoutesMixin"

// create an extended `Vue` constructor
const localVue = createLocalVue();
localVue.use(routeMixin)

jest.mock("axios", () => ({
  get: () => Promise.resolve({ card: {info: {title: "this is the title"}}})
}));


describe("CardBilledBeforeSigned.vue", () => {
  it("mocking the axios call to get card dto", () => {
    var wrapper = shallowMount(CardBilledBeforeSigned, {localVue});
  
  
  });
});

and here is the component I'm testing

<template>
  <data-card
    :loading="loading"
    :table-view="tableView"
    :chart-view="chartView"
    :card="card"
  />
</template>
<script>
import DataCardModel from "../../../models/metrics/datacard/DataCard";
import DataCard from "./DataCard";
export default {
  components: { DataCard },
  props: ["users", "startDate", "endDate", "chartView", "tableView"],
  data() {
    return {
      loading: true,
      card: new DataCardModel(),
    };
  },
  methods: {
    get() {
      this.loading = true;
      this.globalRoute(
        "route.needed"
      ).then((route) => {
        axios
          .get(route, {
            params: {
              users: this.users,
              start_date: this.startDate,
              end_date: this.endDate,
            },
          })
          .then((response) => {
            if (response.data.status == "success") {
              let { card } = response.data.payload;
              this.card.fill(card);
              console.log(this.card);
            }
            this.loading = false;
          })
          .catch((error) => {
            console.log(error);
            this.errors = "Error - Notify Tech Team ";
          });
      });
    },
  },
  watch: {},
  mounted() {
    this.get();
  },
};
</script>

<style>
</style>

Also, any advice on the best way to test a component like this would be helpful. Thanks,

0 likes
1 reply
ronaldgevern's avatar

The original concept of promises was that you could have a rejected promise sitting around for some time before attaching a catch handler to it. For example, Firefox used to warn of uncaught rejection errors only when a rejected promise with no rejection handler was garbage collected from memory.

Somebody decided that JavaScript programmers couldn't be trusted with managing promise rejections properly and changed the HTML spec to require browsers to throw "unhandled promise rejection" errors if a rejected promise has no rejection handlers added before code returns to the event loop.

On a case by case basis you can prevent the host being notified by adding a rejection handler that is never used. The reasoning is that adding a dummy rejection handler to a promise means that should it be rejected it has a rejection handler already - or if it was rejected the host is notified the promise now has a rejection handler - and you can call then and catch multiple times on the same promise.

A nice way to wait for several Promises to resolve to use the Promise.all function. It expects an Array of Promises, and produces a Promise that resolves to an Array containing the values that the individual Promises resolved to. Furthermore, it only resolves after the last Promise resolves. If any of its input Promises rejects, then the entire Promise.all expression rejects as well. It effectively "runs" all of its input processes "at the same time", emulating the classic "fork-join" pattern.

http://net-informations.com/js/iq/default.htm

Please or to participate in this conversation.