negabaro
negabaro

Reputation: 3965

How to mock variables in action of vuex store with jest

I have a js code like this:

const Repository = axios.create( {
  baseURL: process.env.VUE_APP_API_HOST
} );

const state = { ... }
const getters = { ... }
const mutations = { ... }


const actions = {
  fetch: async ( { commit, getters }, { apiPath, id } ) => {

    const response = await Repository.get( apiPath );

    commit( 'setArticleList', { response.data, id } );
    commit( 'changeApiStatus', { status: 'success', id } );
  }
};

export const articleList = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};

I have a jest code like this:

import { store as store2 } from './store';

describe( 'store article_list test: ', () => {

  let store;
  beforeEach( () => {
    store = new Vuex.Store( store2 );
  } );

  describe( 'test actions', () => {
    test( 'get value correctly', async () => {
      const apiPath = 'api/v1/article_list.json';
      const id = 1;
        await store.dispatch( 'articleList/fetch', { apiPath, id } );
    } );
  } );


} );

this is store code:

store.js

import Vue from 'vue';
import Vuex from 'vuex';
import { articleList } from '@/store/modules/article_list';

Vue.use( Vuex );

export const store = {
  modules: {
    articleList
  }
};
export default new Vuex.Store( store );

await store.dispatch( 'articleList/fetch', { apiPath, id } );

Currently this code has an Error: Error: connect ECONNREFUSED 127.0.0.1: 8080 error

I would like to mock this part const response = await Repository.get( apiPath );

But I have no idea how to mock variables in action of vuex store with jest.

Let me know if you know how to mock this part.

Thanks for reading my question.

Upvotes: 1

Views: 979

Answers (1)

Rich
Rich

Reputation: 562

I'm using moxios to mock my axios requests, works pretty well, it allows you to set your own response data.

Upvotes: 1

Related Questions