0

I have a test that is passing, but I don't understand why I have to write this way. Here is the test setup:

describe("Photo Due", () => {
  const localVue = createLocalVue();
  localVue.use(Vuex);
  let store;
  let actions = {
    "api_data/photoAction": jest.fn(),
    "api_data/selectPhoto": jest.fn(),
    "modals/openCloseModal": jest.fn()
  },
  beforeEach(() => {
    store = new Vuex.Store({
      state: {
        token: "abc",
        GLN: "123",
        GLT: "456",
        isDesktop: true
      },
      getters: {
        "auth/getToken": state => state.token,
        "auth/getGLN": state => state.GLN,
        "auth/getGLT": state => state.GLT,
        "app/getIsDesktop": state => state.isDesktop
      },
      actions
    });
  });
...

Here is my test that calls a function, which calls an action:

it("reportPhoto", async () => {
    const wrapper = factory();
    wrapper.vm.reportPhoto();
    wrapper.vm.$nextTick();
    expect(actions["api_data/selectPhoto"]).toHaveBeenCalled();  // THIS IS THE LINE IN QUESTION
  });

When the test is setup this way everything passes. But it doesn't seem right that I am defining actions outside of the store and accessing it that way in the test by calling actions["api_data/selectSnap"]. I copied this approach from a guide on from the vue-test-utils website. If I don't need to access actions and getters from the store then why not bypass the store altogether and jut define random functions that mock my vuex functionality?

I think I don't understand what is happening under the hood fully, but shouldn't I be accessing the action through the store? This is what I am having trouble doing.

My questions are 1) Do I need to access the actions through the store or am I overthinking what should be a basic test? 2) If I do need to access the action through the store, how do I go about doing that?

jcdl
  • 680
  • 1
  • 5
  • 16
Brian
  • 385
  • 1
  • 5
  • 23
  • There is a slightly different approach described in the Vuex documentation: https://vuex.vuejs.org/guide/testing.html – jcdl Jul 29 '20 at 20:51
  • 1
    I would actually recommend a different guide: [https://vue-test-utils.vuejs.org/guides/using-with-vuex.html#testing-a-running-store](https://vue-test-utils.vuejs.org/guides/using-with-vuex.html#testing-a-running-store). This is truly testing your existing store to the fullest, but presents its own challenges. – Ohgodwhy Jul 29 '20 at 20:52

1 Answers1

0

It really depends on what kind of test you are trying to do and if you want to test a fully functional store or just check that it gets called.

I recommend this post. There are differents approach explained along with several examples. It helped me when I needed to write some store oriented unit tests

kliank
  • 31
  • 5