I have a Vue single-page application (SPA) that utilizes Pinia as a store. The application also establishes a global namespace gapi
by including a Google API script tag: https://developers.google.com/drive/api/quickstart/js
This means that in my store, I will have code similar to:
function gapiLoaded() {
gapi.load('client', initializeGapiClient);
}
During test functions, components make use of the store using the useStore
paradigm. Consequently, when running my test suite, I encounter errors such as gapi is not defined
.
Here is 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);
});
});
Although I have tried to mock the gapi
according to the vue-test-util documentation, it seems that the documentation may only cover globals referenced by components and not those referenced by a store file.
I attempted to find if createTestingPinia
offers a global mock option, but there is no mention of it in the docs: . Unfortunately, I was unable to locate comprehensive documentation on this function.
In a @pinia/testing + vue-test-utils test file, how can I mock globals referenced within a Pinia store file?
The entire codebase is open source if more context is needed: