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