javascriptvue.jsunit-testingpiniavue-test-utils

In a Vue "Composition" + Pinia "Setup Function" SPA, how can I mock a global referenced in a store, such as `gapi`?


I have a Vue SPA using Pinia as a store. The application also creates a global namespace gapi via a google API script tag: https://developers.google.com/drive/api/quickstart/js

Thus in my store, I'll have code such as

  function gapiLoaded() {
    gapi.load('client', initializeGapiClient);
  }

In my test functions, I'll have components that leverage the store, via the useStore paradigm. Thus my store code is run, and I get errors such as gapi is not defined when I run my test suite.

Here's an example test file:

import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import Files from '../Files.vue';
import type { ReadFile } from '../Files.vue';
import { createTestingPinia } from '@pinia/testing';
// import any store you want to interact with in tests
import { useDriveStore } from '@/stores/drive';
import { fn } from '@vitest/spy';

describe('Files Component', () => {

  it('renders properly', () => {
    const wrapper = mount(Files, {
      global: {
        plugins: [
          createTestingPinia({
            createSpy: fn,
            initialState: {
              drive: {
                files: [
                  {
                    name: 'test file 1',
                    id: '1'
                  },
                  {
                    name: 'test file 2',
                    id: '2'
                  }
                ]
              }
            }
          })
        ],
        mocks: {
          gapi: {
            load: function() {},
            client: {
              init: function() {},
            }
          }
        }
      }
    });
    const store = useDriveStore(); // uses the testing pinia!
    const filesList = '[data-testid=files-list]';
    expect(store.fetchFiles).toHaveBeenCalledTimes(1);
    expect(wrapper.find(filesList).text()).toContain('test file 1');
    expect(wrapper.findAll('[data-testid=files-item]')).toHaveLength(2);
  });
});

As you can see, I've attempted to mock the gapi per the vue-test-util docs, however, perhaps vue-test-util docs are referring to globals referenced by components, and isn't equipped to handle globals referenced by a store file.

I tried to see if createTestingPinia allowed some sort of global mock option, but the docs don't mention it: https://pinia.vuejs.org/cookbook/testing.html and I failed to find comprehensive documentation on the function.

How can I, in a @pinia/testing + vue-test-utils test file, mock globals referenced within a pinia store file?

The entire codebase is FOSS if it helps to have more context: https://codeberg.org/calebrogers/vue-google-drive


Solution

  • This isn't related to Vue or Pinia-specific testing utilities. There is gapi variable or import, and it's supposed to be mocked.

    Speaking generally, any dependencies that are supposed to be replaced at some point, including tests, can be made injectable. DI for testability reasons isn't the case for Jest/Vitest due to the availability of mocking at module level. It can be trickier to conditionally mock an import depending on a test, but third-party libraries should generally be fully mocked in unit tests, especially the ones that heavily rely on DOM like gapi, because there's no real DOM in testing environment.

    gapi is a global and it can be mocked at the top of test suite:

    beforeEach(() => 
      globalThis.gapi = {
        load: vi.fn()
      }
    });