Tips for monitoring dispatch in fetch/middleware functions

Just testing a basic webpage

<template>
  <HomeTemplate />
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  async fetch(context) { // or middleware(context)
    await context.store.dispatch('categories/index')
  }
})
</script>

Want to monitor dispatch and ensure everything goes smoothly, initially tried spying on the action only:

import { Wrapper, shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex, { Store } from 'vuex'
import HomePage from './index.vue'
import { CategoriesState } from '@/store/categories'

const localVue = createLocalVue()
localVue.use(Vuex)

describe('HomePage', () => {
  type Instance = InstanceType<typeof HomePage>
  let wrapper: Wrapper<Instance>

  let store: Store<CategoriesState>

  const mockIndex: jest.Mock = jest.fn()

  beforeAll(() => {
    store = new Vuex.Store({
      modules: {
        categories: {
          namespaced: true,
          actions: { index: mockIndex }
        }
      }
    })

    wrapper = shallowMount(HomePage, {
      stubs: ['HomeTemplate'],
      localVue,
      store
    })
  })

  it('should call vuex action to fetch categories', () => {
    expect(mockIndex).toHaveBeenCalledWith('categories/index')
  })
})

Considering that the fetch() or middleware() method receives the nuxt context, attempted to mock it

import { Wrapper, shallowMount } from '@vue/test-utils'
import HomePage from './index.vue'

describe('HomePage', () => {
  type Instance = InstanceType<typeof HomePage>
  let wrapper: Wrapper<Instance>

  const mockIndex: jest.Mock = jest.fn()

  beforeAll(() => {
    wrapper = shallowMount(HomePage, {
      stubs: ['HomeTemplate'],
      mocks: {
        context: {
          store: {
            dispatch: mockIndex
          }
        }
      }
    })
  })

  it('should call vuex action to fetch categories', () => {
    expect(mockIndex).toHaveBeenCalledWith('categories/index')
  })
})

Still facing issues, https://i.sstatic.net/qivTC.png

Any assistance in resolving this would be greatly appreciated!

Thank you!

Answer №1

fetch is a unique Nuxt-specific hook that is not recognized by @vue/test-utils. Calling mockIndex in tests is not expected unless the hook is explicitly triggered.

A correct usage would be:

const context = {
  store: {
    dispatch: mockIndex
  }
};

await HomePage.options.fetch(context);
expect(mockIndex).toBeCalledWith(...)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format. Current Output let temp = [ { "imagePath": "", "imageDescription": [ { "language": "en ...

TypeScript disregards interface method argument types

Unexpectedly, the code below compiles without any errors (using tsc 3.9.5): interface IDateHandler { handleDate: (Date) => void; } let dateHandler: IDateHandler = { handleDate: (d: Date) => {}, }; dateHandler.handleDate([1, 2, 3]); Even more s ...

Unable to transfer props object to React component using TypeScript

Apologies if this seems like a basic issue, but I've been struggling with it for the past two days. I'm currently working on writing a simple unit test in Vitest that involves rendering a component to the screen and then using screen.debug(). The ...

utilizing axios to send multiple data using flask api and vuejs

I am trying to retrieve the context_answers and treatment_answers from user inputs on my website and send them to Flask. As a beginner, I apologize if my explanation is unclear about what I am attempting. `context_answers = {"a":[1], "b":[2], "c":[3], "d" ...

Enhanced VS code typings for Nuxt injected properties

My approach to injecting properties into the Nuxt TS context is as follows: ~/plugins/services.ts import Vue from 'vue'; import { errorService } from '~/services/error'; import { Plugin } from '@nuxt/types' const services: Pl ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Using Typescript to retrieve the Return Type of a function when called with specific Parameter types

My goal is to create 2 interfaces for accessing the database: dao can be used by both admins and regular users, so each function needs an isAdmin:boolean parameter (e.g. updateUser(isAdmin: boolean, returnUser)) daoAsAdmin, on the other hand, allows metho ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

Creating hierarchical TreeNode structure in TypeScript

As I work with a flat one-dimensional array of type TreeNode (view interface definition below), my goal is to recursively traverse the array and add subsequent array elements as children. While attempting a non-recursive approach using a buffer, I encount ...

Creating HTML elements dynamically based on the value of a prop within a React component

In my React component built using Typescript, it takes in three props: type, className, and children The main purpose of this component is to return an HTML element based on the value passed through type. Below is the code for the component: import React ...

Sharing OAuth token between Vue.js components

Once the OAuth login is successful, I retrieve the OAuth token in the SuccessOAuth.vue component. The token details are obtained as shown below: checkforTokens(){ const queryString = this.$route.query; console.log(query ...

The specific property 'splice' cannot be found within type 'T'

As I delve into working with TypeScript, an unexpected error arises: Property 'splice' does not exist on type 'T'. type Item = { name: string, body: string, imgOne: string, imgTwo: string, }[] // Another file contains this func ...

The member 'pipe' is not found within the 'AngularFireObject<{}>' type

As someone new to Angular, I've been following a tutorial by Mosh Hamedani on version 6 of Angular, but unfortunately the tutorial is based on version 4. Currently, I'm working on an e-commerce project that involves implementing an AddToCart butt ...

Discovering a method to detect clicks outside of a React functional component

Looking to identify when a click occurs outside of a React functional component. After stumbling upon an article, I followed the provided code but unfortunately, it didn't work as expected. Despite identifying the issue, I am still searching for a so ...

Elements with absolute positioning are preventing drag events from executing

Struggling to create a slider and encountering an issue. The problem lies in absolute items blocking slider drag events. I need a solution that allows dragging the underlying image through absolute positioned items. Any ideas on how to achieve this? MANY T ...

How can I retrieve a value from the main model and assign it to an object in

I'm facing a simple dilemma. I want to extract the data from the main area of my Vue model and place it inside an object. I've tried using app.$data.name and also this.name, but unfortunately, I haven't been able to make it work without enco ...

Strict type inference for the number data type in TypeScript

I am interested in inferring the number type within this function: type Options = { count: number }; function bar<C extends Options>(options: C): C['count'] extends 3 ? 'x' : 'y' {} bar({ count: 3 }) // x bar({ count: ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...

When attempting to install Vue Js, I encounter the following npm error

I recently set up Node.js using Snap on my Parrot OS system. However, I've noticed that the node_modules folder is missing after /usr/local/lib When running npm install -g @vue/cli, I encountered this error: npm WARN deprecated @hapi/[email pro ...

What is the best way to set up a task scheduler using node-cron in a Vue.js

Following the documentation in Node.js, each * symbol has a specific meaning. cron.schedule('* * * * *', () => { console.log('running a task every minute'); }); # ┌────────────── second (optional) # ...