0
0
Fork 0

Updated unit tests

This commit is contained in:
Joan Sanchez 2022-12-13 12:21:12 +01:00
parent 18a717f40d
commit fd8ed1c638
8 changed files with 111 additions and 119 deletions

1
.gitignore vendored
View File

@ -1,6 +1,7 @@
.DS_Store .DS_Store
.thumbs.db .thumbs.db
node_modules node_modules
junit.xml
# Quasar core related directories # Quasar core related directories
.quasar .quasar

View File

@ -1,4 +1,5 @@
<script setup> <script setup>
import { onMounted } from 'vue';
import axios from 'axios'; import axios from 'axios';
import { useQuasar } from 'quasar'; import { useQuasar } from 'quasar';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@ -8,9 +9,22 @@ import { useSession } from 'src/composables/useSession';
const quasar = useQuasar(); const quasar = useQuasar();
const router = useRouter(); const router = useRouter();
const session = useSession(); const session = useSession();
const { t } = useI18n(); const { t, availableLocales, locale, fallbackLocale } = useI18n();
const { isLoggedIn } = session; const { isLoggedIn } = session;
onMounted(() => {
let userLang = window.navigator.language;
if (userLang.includes('-')) {
userLang = userLang.split('-')[0];
}
if (availableLocales.includes(userLang)) {
locale.value = userLang;
} else {
locale.value = fallbackLocale;
}
});
quasar.iconMapFn = (iconName) => { quasar.iconMapFn = (iconName) => {
if (iconName.startsWith('vn:')) { if (iconName.startsWith('vn:')) {
const name = iconName.substring(3); const name = iconName.substring(3);

View File

@ -11,21 +11,14 @@ const session = useSession();
jest.mock('vue-router', () => ({ jest.mock('vue-router', () => ({
useRouter: () => ({ useRouter: () => ({
push: mockPush, push: mockPush,
currentRoute: { value: 'myCurrentRoute' } currentRoute: { value: 'myCurrentRoute' },
}), }),
})); }));
jest.mock('src/composables/useSession', () => ({ jest.mock('src/composables/useSession', () => ({
useSession: () => ({ useSession: () => ({
isLoggedIn: mockLoggedIn, isLoggedIn: mockLoggedIn,
destroy: mockDestroy destroy: mockDestroy,
}),
}));
jest.mock('vue-i18n', () => ({
createI18n: () => { },
useI18n: () => ({
t: () => { }
}), }),
})); }));
@ -34,11 +27,10 @@ describe('App', () => {
beforeAll(() => { beforeAll(() => {
const options = { const options = {
global: { global: {
stubs: ['router-view'] stubs: ['router-view'],
} },
}; };
vm = createWrapper(App, options).vm; vm = createWrapper(App, options).vm;
}); });
it('should return a login error message', async () => { it('should return a login error message', async () => {
@ -48,17 +40,17 @@ describe('App', () => {
const response = { const response = {
response: { response: {
status: 401 status: 401,
} },
}; };
expect(vm.responseError(response)).rejects.toEqual(expect.objectContaining(response)); expect(vm.responseError(response)).rejects.toEqual(expect.objectContaining(response));
expect(vm.quasar.notify).toHaveBeenCalledWith(expect.objectContaining( expect(vm.quasar.notify).toHaveBeenCalledWith(
{ expect.objectContaining({
message: 'Invalid username or password',
type: 'negative', type: 'negative',
message: 'login.loginError' })
} );
));
}); });
it('should return an unauthorized error message', async () => { it('should return an unauthorized error message', async () => {
@ -68,17 +60,17 @@ describe('App', () => {
const response = { const response = {
response: { response: {
status: 401 status: 401,
} },
}; };
expect(vm.responseError(response)).rejects.toEqual(expect.objectContaining(response)); expect(vm.responseError(response)).rejects.toEqual(expect.objectContaining(response));
expect(vm.quasar.notify).toHaveBeenCalledWith(expect.objectContaining( expect(vm.quasar.notify).toHaveBeenCalledWith(
{ expect.objectContaining({
message: 'Access denied',
type: 'negative', type: 'negative',
message: 'errors.statusUnauthorized' })
} );
));
expect(session.destroy).toHaveBeenCalled(); expect(session.destroy).toHaveBeenCalled();
}); });

View File

@ -3,9 +3,11 @@ import { createI18n } from 'vue-i18n';
import messages from 'src/i18n'; import messages from 'src/i18n';
const i18n = createI18n({ const i18n = createI18n({
locale: 'es', locale: 'en',
fallbackLocale: 'en',
messages, messages,
legacy: false legacy: false,
missingWarn: false
}); });
export default boot(({ app }) => { export default boot(({ app }) => {
@ -13,4 +15,4 @@ export default boot(({ app }) => {
app.use(i18n); app.use(i18n);
}); });
export { i18n }; export { i18n };

View File

@ -22,9 +22,8 @@ const props = defineProps({
}, },
}); });
onMounted(async () => { onMounted(() => {
await navigation.fetchPinned(); navigation.fetchPinned().then(getRoutes());
getRoutes();
}); });
function findMatches(search, item) { function findMatches(search, item) {
@ -48,11 +47,13 @@ function addChildren(module, route, parent) {
if (route.menus) { if (route.menus) {
const mainMenus = route.menus[props.source]; const mainMenus = route.menus[props.source];
const matches = findMatches(mainMenus, route); const matches = findMatches(mainMenus, route);
for (const child of matches) { for (const child of matches) {
navigation.addMenuItem(module, child, parent); navigation.addMenuItem(module, child, parent);
} }
} }
} }
const pinnedItems = computed(() => { const pinnedItems = computed(() => {
return items.value.filter((item) => item.isPinned); return items.value.filter((item) => item.isPinned);
}); });
@ -61,11 +62,13 @@ const items = ref([]);
function getRoutes() { function getRoutes() {
if (props.source === 'main') { if (props.source === 'main') {
const modules = Object.assign([], navigation.getModules().value); const modules = Object.assign([], navigation.getModules().value);
for (const item of modules) { for (const item of modules) {
const moduleDef = routes.find((route) => toLowerCamel(route.name) === item.module); const moduleDef = routes.find((route) => toLowerCamel(route.name) === item.module);
item.children = []; item.children = [];
if (!moduleDef) continue;
addChildren(item.module, moduleDef, item.children); addChildren(item.module, moduleDef, item.children);
} }
@ -77,6 +80,8 @@ function getRoutes() {
const currentModule = toLowerCamel(currentRoute.name); const currentModule = toLowerCamel(currentRoute.name);
const moduleDef = routes.find((route) => toLowerCamel(route.name) === currentModule); const moduleDef = routes.find((route) => toLowerCamel(route.name) === currentModule);
if (!moduleDef) return;
addChildren(currentModule, moduleDef, items.value); addChildren(currentModule, moduleDef, items.value);
} }
} }

View File

@ -3,7 +3,6 @@ import { createWrapper } from 'app/tests/jest/jestHelpers';
import Leftmenu from '../LeftMenu.vue'; import Leftmenu from '../LeftMenu.vue';
import { createTestingPinia } from '@pinia/testing'; import { createTestingPinia } from '@pinia/testing';
import { createI18n } from 'vue-i18n';
import { useNavigationStore } from 'src/stores/useNavigationStore'; import { useNavigationStore } from 'src/stores/useNavigationStore';
const mockPush = jest.fn(); const mockPush = jest.fn();
@ -18,49 +17,38 @@ jest.mock('vue-router', () => ({
}), }),
})); }));
jest.mock('src/router/routes', () => [ jest.mock('src/router/modules', () => [
{ {
path: '/', path: '/customer',
name: 'Main', name: 'Customer',
meta: {
title: 'customers',
icon: 'vn:client',
},
menus: {
main: ['CustomerList', 'CustomerCreate'],
card: ['CustomerBasicData'],
},
children: [ children: [
{ {
path: '/dashboard', path: '',
name: 'Dashboard', name: 'CustomerMain',
meta: { title: 'dashboard', icon: 'dashboard' },
},
{
path: '/customer',
name: 'Customer',
meta: {
title: 'customers',
icon: 'vn:client',
},
menus: {
main: ['CustomerList', 'CustomerCreate'],
card: ['CustomerBasicData'],
},
children: [ children: [
{ {
path: '', path: 'list',
name: 'CustomerMain', name: 'CustomerList',
children: [ meta: {
{ title: 'list',
path: 'list', icon: 'view_list',
name: 'CustomerList', },
meta: { },
title: 'list', {
icon: 'view_list', path: 'create',
}, name: 'CustomerCreate',
}, meta: {
{ title: 'createCustomer',
path: 'create', icon: 'vn:addperson',
name: 'CustomerCreate', },
meta: {
title: 'createCustomer',
icon: 'vn:addperson',
},
},
],
}, },
], ],
}, },
@ -70,57 +58,47 @@ jest.mock('src/router/routes', () => [
describe('Leftmenu', () => { describe('Leftmenu', () => {
let vm; let vm;
beforeAll(() => { let navigation;
const i18n = createI18n({ beforeAll(async () => {
legacy: false,
messages: {
'en-US': {
globals: {
pinnedModules: 'Test',
},
moduleIndex: {
allModules: 'All modules',
},
},
},
});
vm = createWrapper(Leftmenu, { vm = createWrapper(Leftmenu, {
propsData: { propsData: {
source: 'main', source: 'main',
}, },
global: { global: {
plugins: [i18n, createTestingPinia()], plugins: [createTestingPinia({ stubActions: false })],
}, },
}).vm; }).vm;
try { navigation = useNavigationStore();
const navigation = useNavigationStore(); navigation.modules = ['customer']; // I should mock to have just one module but isn´t working
navigation.getModules(); navigation.fetchPinned = jest.fn().mockReturnValue(Promise.resolve(true));
} catch (error) { navigation.getModules = jest.fn().mockReturnValue({
console.log('err!'); value: [
} {
name: 'customer',
title: 'customer.pageTitles.customers',
icon: 'vn:customer',
module: 'customer',
},
],
});
}); });
it('should return a proper formated object with two child items', async () => { it('should return a proper formated object with two child items', async () => {
const expectedMenuItem = [ const expectedMenuItem = [
{ {
name: 'CustomerList', name: 'CustomerList',
title: 'list', title: 'customer.pageTitles.list',
icon: 'view_list', icon: 'view_list',
stateName: 'CustomerList',
}, },
{ {
name: 'CustomerCreate', name: 'CustomerCreate',
title: 'createCustomer', title: 'customer.pageTitles.createCustomer',
icon: 'vn:addperson', icon: 'vn:addperson',
stateName: 'CustomerCreate',
}, },
]; ];
const secondMenuItem = vm.items; const firstMenuItem = vm.items[0];
expect(secondMenuItem.length).toEqual(1); expect(firstMenuItem.children).toEqual(expect.arrayContaining(expectedMenuItem));
//expect(secondMenuItem.children).toEqual(expect.arrayContaining(expectedMenuItem));
//expect(secondMenuItem.children.length).toEqual(2);
}); });
}); });

View File

@ -12,9 +12,10 @@ export const useNavigationStore = defineStore('navigationStore', () => {
function getModules() { function getModules() {
const modulesRoutes = ref([]); const modulesRoutes = ref([]);
console.log('routes', routes);
for (const module of modules) { for (const module of modules) {
const moduleDef = routes.find((route) => toLowerCamel(route.name) === module); const moduleDef = routes.find((route) => toLowerCamel(route.name) === module);
if (!moduleDef) continue;
const item = addMenuItem(module, moduleDef, modulesRoutes.value); const item = addMenuItem(module, moduleDef, modulesRoutes.value);
if (!item) continue; if (!item) continue;

View File

@ -1,25 +1,27 @@
import { mount, flushPromises } from '@vue/test-utils'; import { mount, flushPromises } from '@vue/test-utils';
import { installQuasarPlugin } from '@quasar/quasar-app-extension-testing-unit-jest'; import { installQuasarPlugin } from '@quasar/quasar-app-extension-testing-unit-jest';
import { i18n } from 'src/boot/i18n'; import { i18n } from 'src/boot/i18n';
import { Notify } from 'quasar'; import { Notify, Dialog } from 'quasar';
import axios from 'axios'; import axios from 'axios';
// Specify here Quasar config you'll need to test your component
installQuasarPlugin({ installQuasarPlugin({
plugins: { plugins: {
Notify Notify,
} Dialog,
},
}); });
export function createWrapper(component, options) { export function createWrapper(component, options) {
const mountOptions = { const mountOptions = {};
global: {
plugins: [i18n]
}
};
if (options instanceof Object) if (options instanceof Object) Object.assign(mountOptions, options);
Object.assign(mountOptions, options)
if (mountOptions.global && mountOptions.global.plugins) {
mountOptions.global.plugins.push(i18n);
} else {
if (!mountOptions.global) mountOptions.global = {};
mountOptions.global.plugins = [i18n];
}
const wrapper = mount(component, mountOptions); const wrapper = mount(component, mountOptions);
const vm = wrapper.vm; const vm = wrapper.vm;
@ -27,7 +29,4 @@ export function createWrapper(component, options) {
return { vm, wrapper }; return { vm, wrapper };
} }
export { export { axios, flushPromises };
axios,
flushPromises
}