salix-front/test/vitest/helper.js

134 lines
3.4 KiB
JavaScript

import { installQuasarPlugin } from '@quasar/quasar-app-extension-testing-unit-vitest';
import { mount, flushPromises } from '@vue/test-utils';
import { createTestingPinia } from '@pinia/testing';
import { vi } from 'vitest';
import { i18n } from 'src/boot/i18n';
import { Notify, Dialog } from 'quasar';
import keyShortcut from 'src/boot/keyShortcut';
import * as useValidator from 'src/composables/useValidator';
installQuasarPlugin({
plugins: {
Notify,
Dialog,
},
});
const pinia = createTestingPinia({ createSpy: vi.fn, stubActions: false });
const mockPush = vi.fn();
const mockReplace = vi.fn();
vi.mock('vue', async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
inject: vi.fn((key) => {
if (key === 'app') {
return {};
}
return actual.inject(key);
}),
onMounted: vi.fn((fn) => (fn && typeof fn === 'function' ? fn() : undefined)),
onBeforeMount: vi.fn((fn) => (fn && typeof fn === 'function' ? fn() : undefined)),
onUpdated: vi.fn((fn) => (fn && typeof fn === 'function' ? fn() : undefined)),
onUnmounted: vi.fn((fn) => (fn && typeof fn === 'function' ? fn() : undefined)),
onBeforeUnmount: vi.fn((fn) =>
fn && typeof fn === 'function' ? fn() : undefined,
),
};
});
vi.mock('vue-router', () => ({
useRouter: () => ({
push: mockPush,
replace: mockReplace,
currentRoute: {
value: {
params: {
id: 1,
},
meta: { moduleName: 'mockModuleName' },
matched: [{ path: 'mockName/list' }],
},
},
}),
useRoute: () => ({
matched: [],
query: {},
params: {},
meta: { moduleName: 'mockModuleName', title: 'mockTitle', name: 'mockName' },
path: 'mockSection/list',
}),
onBeforeRouteLeave: () => {},
}));
vi.spyOn(useValidator, 'useValidator').mockImplementation(() => {
return {
validate: vi.fn(),
validations: () => ({
format: vi.fn(),
presence: vi.fn(),
required: vi.fn(),
length: vi.fn(),
numericality: vi.fn(),
min: vi.fn(),
custom: vi.fn(),
}),
};
});
class FormDataMock {
append() {
vi.fn();
}
delete() {
vi.fn();
}
get() {
vi.fn();
}
getAll() {
vi.fn();
}
has() {
vi.fn();
}
set() {
vi.fn();
}
forEach() {
vi.fn();
}
}
global.FormData = FormDataMock;
global.URL = class URL {};
global.Date.vnNew = () => new Date(Date.UTC(2001, 0, 1, 11));
export function createWrapper(component, options) {
const defaultOptions = {
global: {
plugins: [i18n, pinia],
directives: {
shortcut: keyShortcut,
},
stubs: ['useState', 'arrayData', 'useStateStore', 'vue-i18n', 'RouterLink'],
},
mocks: {
t: (tKey) => tKey,
$t: (tKey) => tKey,
},
};
const mountOptions = {
...defaultOptions,
...options,
global: { ...defaultOptions.global, ...options?.global },
};
const wrapper = mount(component, mountOptions);
const vm = wrapper.vm;
return { vm, wrapper };
}
export { flushPromises };