lundi 15 juin 2020

How to test namespaced mapAction in Vue

I have a namespaced Vuex store in my Vue 2.6 app one module of which is like this:

 //books.js

 export default {
  state: {
    books: null
  },
  mutations: {
    SET_BOOKS(state, books) {
      state.books = books;
    },
  },
  actions: {
    setBooks: async function ({ commit }) {
      //api call
      commit('SET_BOOKS', books);
    }
  },
  namespaced: true
};

I want to test a component that calls the setBooks action. I am using mapActions to access the actions. The relevant code is:

 //Books.vue

 methods: {
    ...mapActions("books", ["setBooks"]),
    }
  },
  created: async function() {
    await this.setBooks();
  }

The problem is that my test can't find the action:

import { shallowMount } from '@vue/test-utils';
import Books from '@/views/Books';
import localVue from '../localVue';
import Vuex from 'vuex';
import flushPromises from 'flush-promises';

describe('Books', () => {

  let actions;
  let store;
  let wrapper;
  beforeEach(() => {
    store = new Vuex.Store({
      state: {
        books: {
          books: null
        }
      },
      actions: {
        setBooks: jest.fn()
      }
    });
    wrapper = shallowMount(Books, { store, localVue })
  });

  it("renders the books", async () => {
    await flushPromises();
    expect(actions.setBooks).toHaveBeenCalled();
  });
});

I get an error [vuex] module namespace not found in mapActions(): books/

if I try to namespace the actions code in the my test to:

actions: {
    books: {
        setBooks: jest.fn()
    }
}

I get TypeError: Cannot read property 'setBooks' of undefined

Please help, thank you!

Aucun commentaire:

Enregistrer un commentaire