Generate question bank domain model from JDL

This commit is contained in:
jieun committed 2026-10-20 18:46:29 +09:00
1 parent 1d97cc4e31
commit 1d74d8f04b
160 files changed
+26900 -2

No files matched your search

@@ -0,0 +1,91 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type RouteLocation } from 'vue-router';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import AlertService from '@/shared/alert/alert.service';
import QuestionDetails from './question-details.vue';
type QuestionDetailsComponentType = InstanceType<typeof QuestionDetails>;
let route: Partial<RouteLocation>;
const routerGoMock = vi.fn();
vi.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const questionSample = { id: 123 };
describe('Component Tests', () => {
let alertService: AlertService;
afterEach(() => {
vi.resetAllMocks();
});
describe('Question Management Detail Component', () => {
let questionServiceStub: any;
let mountOptions: MountingOptions<QuestionDetailsComponentType>['global'];
beforeEach(() => {
route = {};
questionServiceStub = {
find: vi.fn(),
};
alertService = new AlertService({
i18n: { t: vi.fn() } as any,
toast: {
create: vi.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'router-link': true,
},
provide: {
alertService,
questionService: () => questionServiceStub,
},
};
});
describe('Navigate to details', () => {
it('Should call load all on init', async () => {
// GIVEN
questionServiceStub.find.mockResolvedValue(questionSample);
route = {
params: {
questionId: `${123}`,
},
};
const wrapper = shallowMount(QuestionDetails, { global: mountOptions });
const comp = wrapper.vm;
// WHEN
await comp.$nextTick();
// THEN
expect(comp.question).toMatchObject(questionSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
questionServiceStub.find.mockResolvedValue(questionSample);
const wrapper = shallowMount(QuestionDetails, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,42 @@
import { type Ref, defineComponent, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useAlertService } from '@/shared/alert/alert.service';
import { type IQuestion } from '@/shared/model/question.model';
import QuestionService from './question.service';
export default defineComponent({
name: 'QuestionDetails',
setup() {
const questionService = inject('questionService', () => new QuestionService());
const alertService = inject('alertService', () => useAlertService(), true);
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const question: Ref<IQuestion> = ref({});
const retrieveQuestion = async questionId => {
try {
const res = await questionService().find(questionId);
question.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.questionId) {
retrieveQuestion(route.params.questionId);
}
return {
question,
previousState,
t$: useI18n().t,
};
},
});
@@ -0,0 +1,51 @@
<template>
<div class="d-flex justify-content-center">
<div class="col-8">
<div v-if="question">
<h2 class="jh-entity-heading" data-cy="questionDetailsHeading">
<span>{{ t$('questionBankApp.question.detail.title') }}</span> {{ question.id }}
</h2>
<dl class="row-md jh-entity-details">
<dt>
<span>{{ t$('questionBankApp.question.prompt') }}</span>
</dt>
<dd>
<span>{{ question.prompt }}</span>
</dd>
<dt>
<span>{{ t$('questionBankApp.question.explanation') }}</span>
</dt>
<dd>
<span>{{ question.explanation }}</span>
</dd>
<dt>
<span>{{ t$('questionBankApp.question.active') }}</span>
</dt>
<dd>
<span>{{ question.active }}</span>
</dd>
<dt>
<span>{{ t$('questionBankApp.question.subject') }}</span>
</dt>
<dd>
<div v-if="question.subject">
<router-link :to="{ name: 'SubjectView', params: { subjectId: question.subject.id } }">{{
question.subject.name
}}</router-link>
</div>
</dd>
</dl>
<button type="submit" @click.prevent="previousState()" class="btn btn-info" data-cy="entityDetailsBackButton">
<font-awesome-icon icon="arrow-left"></font-awesome-icon>&nbsp;<span>{{ t$('entity.action.back') }}</span>
</button>
<router-link v-if="question.id" :to="{ name: 'QuestionEdit', params: { questionId: question.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>&nbsp;<span>{{ t$('entity.action.edit') }}</span>
</button>
</router-link>
</div>
</div>
</div>
</template>
<script lang="ts" src="./question-details.component.ts"></script>
@@ -0,0 +1,139 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { type RouteLocation } from 'vue-router';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import AlertService from '@/shared/alert/alert.service';
import QuestionUpdate from './question-update.vue';
type QuestionUpdateComponentType = InstanceType<typeof QuestionUpdate>;
let route: Partial<RouteLocation>;
const routerGoMock = vi.fn();
vi.mock('vue-router', () => ({
useRoute: () => route,
useRouter: () => ({ go: routerGoMock }),
}));
const questionSample = { id: 123 };
describe('Component Tests', () => {
let mountOptions: MountingOptions<QuestionUpdateComponentType>['global'];
let alertService: AlertService;
describe('Question Management Update Component', () => {
let comp: QuestionUpdateComponentType;
let questionServiceStub: any;
beforeEach(() => {
route = {};
questionServiceStub = {
retrieve: vi.fn(),
find: vi.fn(),
update: vi.fn(),
create: vi.fn(),
};
questionServiceStub.retrieve.mockResolvedValueOnce([]);
alertService = new AlertService({
i18n: { t: vi.fn() } as any,
toast: {
create: vi.fn(),
} as any,
});
mountOptions = {
stubs: {
'font-awesome-icon': true,
'b-input-group': true,
'b-input-group-prepend': true,
'b-form-datepicker': true,
'b-form-input': true,
},
provide: {
alertService,
questionService: () => questionServiceStub,
subjectService: () => ({
retrieve: vi.fn().mockResolvedValue({}),
}),
},
};
});
afterEach(() => {
vi.resetAllMocks();
});
describe('save', () => {
it('Should call update service on save for existing entity', async () => {
// GIVEN
const wrapper = shallowMount(QuestionUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.question = questionSample;
questionServiceStub.update.mockResolvedValue(questionSample);
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(questionServiceStub.update).toHaveBeenCalledWith(questionSample);
expect(comp.isSaving).toEqual(false);
});
it('Should call create service on save for new entity', async () => {
// GIVEN
const entity = {};
questionServiceStub.create.mockResolvedValue(entity);
const wrapper = shallowMount(QuestionUpdate, { global: mountOptions });
comp = wrapper.vm;
comp.question = entity;
// WHEN
comp.save();
await comp.$nextTick();
// THEN
expect(questionServiceStub.create).toHaveBeenCalledWith(entity);
expect(comp.isSaving).toEqual(false);
});
});
describe('Before route enter', () => {
it('Should retrieve data', async () => {
// GIVEN
questionServiceStub.find.mockResolvedValue(questionSample);
questionServiceStub.retrieve.mockResolvedValue([questionSample]);
// WHEN
route = {
params: {
questionId: `${questionSample.id}`,
},
};
const wrapper = shallowMount(QuestionUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(comp.question).toMatchObject(questionSample);
});
});
describe('Previous state', () => {
it('Should go previous state', async () => {
questionServiceStub.find.mockResolvedValue(questionSample);
const wrapper = shallowMount(QuestionUpdate, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
comp.previousState();
await comp.$nextTick();
expect(routerGoMock).toHaveBeenCalledWith(-1);
});
});
});
});
@@ -0,0 +1,122 @@
import { type Ref, computed, defineComponent, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { useVuelidate } from '@vuelidate/core';
import SubjectService from '@/entities/subject/subject.service';
import { useAlertService } from '@/shared/alert/alert.service';
import { useValidation } from '@/shared/composables';
import { type IQuestion, Question } from '@/shared/model/question.model';
import { type ISubject } from '@/shared/model/subject.model';
import QuestionService from './question.service';
export default defineComponent({
name: 'QuestionUpdate',
setup() {
const questionService = inject('questionService', () => new QuestionService());
const alertService = inject('alertService', () => useAlertService(), true);
const question: Ref<IQuestion> = ref(new Question());
const subjectService = inject('subjectService', () => new SubjectService());
const subjects: Ref<ISubject[]> = ref([]);
const isSaving = ref(false);
const currentLanguage = inject('currentLanguage', () => computed(() => navigator.language ?? 'en'), true);
const route = useRoute();
const router = useRouter();
const previousState = () => router.go(-1);
const retrieveQuestion = async questionId => {
try {
const res = await questionService().find(questionId);
question.value = res;
} catch (error) {
alertService.showHttpError(error.response);
}
};
if (route.params?.questionId) {
retrieveQuestion(route.params.questionId);
}
const initRelationships = () => {
subjectService()
.retrieve()
.then(res => {
subjects.value = res.data;
});
};
initRelationships();
const { t: t$ } = useI18n();
const validations = useValidation();
const validationRules = {
prompt: {
required: validations.required(t$('entity.validation.required').toString()),
minLength: validations.minLength(t$('entity.validation.minlength', { min: 5 }).toString(), 5),
maxLength: validations.maxLength(t$('entity.validation.maxlength', { max: 2000 }).toString(), 2000),
},
explanation: {
maxLength: validations.maxLength(t$('entity.validation.maxlength', { max: 2000 }).toString(), 2000),
},
active: {
required: validations.required(t$('entity.validation.required').toString()),
},
choices: {},
subject: {
required: validations.required(t$('entity.validation.required').toString()),
},
};
const v$ = useVuelidate(validationRules, question as any);
v$.value.$validate();
return {
questionService,
alertService,
question,
previousState,
isSaving,
currentLanguage,
subjects,
v$,
t$,
};
},
created(): void {},
methods: {
save(): void {
this.isSaving = true;
if (this.question.id) {
this.questionService()
.update(this.question)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showInfo(this.t$('questionBankApp.question.updated', { param: param.id }));
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
} else {
this.questionService()
.create(this.question)
.then(param => {
this.isSaving = false;
this.previousState();
this.alertService.showSuccess(this.t$('questionBankApp.question.created', { param: param.id }).toString());
})
.catch(error => {
this.isSaving = false;
this.alertService.showHttpError(error.response);
});
}
},
},
});
@@ -0,0 +1,95 @@
<template>
<div class="d-flex justify-content-center">
<div class="col-8">
<form name="editForm" novalidate @submit.prevent="save()">
<h2 id="questionBankApp.question.home.createOrEditLabel" data-cy="QuestionCreateUpdateHeading">
{{ t$('questionBankApp.question.home.createOrEditLabel') }}
</h2>
<div>
<div class="mb-3" v-if="question.id">
<label for="id">{{ t$('global.field.id') }}</label>
<input type="text" class="form-control" id="id" name="id" v-model="question.id" readonly />
</div>
<div class="mb-3">
<label class="form-control-label" for="question-prompt">{{ t$('questionBankApp.question.prompt') }}</label>
<input
type="text"
class="form-control"
name="prompt"
id="question-prompt"
data-cy="prompt"
:class="{ valid: !v$.prompt.$invalid, invalid: v$.prompt.$invalid }"
v-model="v$.prompt.$model"
required
/>
<div v-if="v$.prompt.$anyDirty && v$.prompt.$invalid">
<small class="form-text text-danger" v-for="error of v$.prompt.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="mb-3">
<label class="form-control-label" for="question-explanation">{{ t$('questionBankApp.question.explanation') }}</label>
<input
type="text"
class="form-control"
name="explanation"
id="question-explanation"
data-cy="explanation"
:class="{ valid: !v$.explanation.$invalid, invalid: v$.explanation.$invalid }"
v-model="v$.explanation.$model"
/>
<div v-if="v$.explanation.$anyDirty && v$.explanation.$invalid">
<small class="form-text text-danger" v-for="error of v$.explanation.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="mb-3 form-check">
<input
type="checkbox"
class="form-check-input"
name="active"
id="question-active"
data-cy="active"
:class="{ valid: !v$.active.$invalid, invalid: v$.active.$invalid }"
v-model="v$.active.$model"
required
/>
<label class="form-check-label" for="question-active">{{ t$('questionBankApp.question.active') }}</label>
<div v-if="v$.active.$anyDirty && v$.active.$invalid">
<small class="form-text text-danger" v-for="error of v$.active.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div class="mb-3">
<label class="form-control-label" for="question">{{ t$('questionBankApp.question.subject') }}</label>
<select class="form-control" id="question-subject" data-cy="subject" name="subject" v-model="question.subject" required>
<option v-if="!question.subject" :value="null" selected></option>
<option
:value="question.subject && subjectOption.id === question.subject.id ? question.subject : subjectOption"
v-for="subjectOption in subjects"
:key="subjectOption.id"
>
{{ subjectOption.name }}
</option>
</select>
</div>
<div v-if="v$.subject.$anyDirty && v$.subject.$invalid">
<small class="form-text text-danger" v-for="error of v$.subject.$errors" :key="error.$uid">{{ error.$message }}</small>
</div>
</div>
<div>
<button type="button" id="cancel-save" data-cy="entityCreateCancelButton" class="btn btn-secondary" @click="previousState()">
<font-awesome-icon icon="ban"></font-awesome-icon>&nbsp;<span>{{ t$('entity.action.cancel') }}</span>
</button>
<button
type="submit"
id="save-entity"
data-cy="entityCreateSaveButton"
:disabled="v$.$invalid || isSaving"
class="btn btn-primary"
>
<font-awesome-icon icon="save"></font-awesome-icon>&nbsp;<span>{{ t$('entity.action.save') }}</span>
</button>
</div>
</form>
</div>
</div>
</template>
<script lang="ts" src="./question-update.component.ts"></script>
@@ -0,0 +1,167 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { type MountingOptions, shallowMount } from '@vue/test-utils';
import AlertService from '@/shared/alert/alert.service';
import Question from './question.vue';
type QuestionComponentType = InstanceType<typeof Question>;
const bModalStub = {
render: () => {},
methods: {
hide: () => {},
show: () => {},
},
};
describe('Component Tests', () => {
let alertService: AlertService;
describe('Question Management Component', () => {
let questionServiceStub: any;
let mountOptions: MountingOptions<QuestionComponentType>['global'];
beforeEach(() => {
questionServiceStub = {
retrieve: vi.fn(),
delete: vi.fn(),
};
questionServiceStub.retrieve.mockResolvedValue({ headers: {} });
alertService = new AlertService({
i18n: { t: vi.fn() } as any,
toast: {
create: vi.fn(),
} as any,
});
mountOptions = {
stubs: {
jhiItemCount: true,
bPagination: true,
bModal: bModalStub as any,
'font-awesome-icon': true,
'b-badge': true,
'jhi-sort-indicator': true,
'b-button': true,
'router-link': true,
},
directives: {
'b-modal': {},
},
provide: {
alertService,
questionService: () => questionServiceStub,
},
};
});
describe('Mount', () => {
it('Should call load all on init', async () => {
// GIVEN
questionServiceStub.retrieve.mockResolvedValue({ headers: {}, data: [{ id: 123 }] });
// WHEN
const wrapper = shallowMount(Question, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(questionServiceStub.retrieve).toHaveBeenCalledOnce();
expect(comp.questions[0]).toEqual(expect.objectContaining({ id: 123 }));
});
it('should calculate the sort attribute for an id', async () => {
// WHEN
const wrapper = shallowMount(Question, { global: mountOptions });
const comp = wrapper.vm;
await comp.$nextTick();
// THEN
expect(questionServiceStub.retrieve.mock.lastCall?.[0]).toMatchObject({
sort: ['id,asc'],
});
});
});
describe('Handles', () => {
let comp: QuestionComponentType;
beforeEach(async () => {
const wrapper = shallowMount(Question, { global: mountOptions });
comp = wrapper.vm;
await comp.$nextTick();
questionServiceStub.retrieve.mockReset();
questionServiceStub.retrieve.mockResolvedValue({ headers: {}, data: [] });
});
it('should load a page', async () => {
// GIVEN
questionServiceStub.retrieve.mockResolvedValue({ headers: {}, data: [{ id: 123 }] });
// WHEN
comp.page = 2;
await comp.$nextTick();
// THEN
expect(questionServiceStub.retrieve).toHaveBeenCalled();
expect(comp.questions[0]).toEqual(expect.objectContaining({ id: 123 }));
});
it('should not load a page if the page is the same as the previous page', () => {
// WHEN
comp.page = 1;
// THEN
expect(questionServiceStub.retrieve).not.toHaveBeenCalled();
});
it('should re-initialize the page', async () => {
// GIVEN
comp.page = 2;
await comp.$nextTick();
questionServiceStub.retrieve.mockReset();
questionServiceStub.retrieve.mockResolvedValue({ headers: {}, data: [{ id: 123 }] });
// WHEN
comp.clear();
await comp.$nextTick();
// THEN
expect(comp.page).toEqual(1);
expect(questionServiceStub.retrieve).toHaveBeenCalledTimes(1);
expect(comp.questions[0]).toEqual(expect.objectContaining({ id: 123 }));
});
it('should calculate the sort attribute for a non-id attribute', async () => {
// WHEN
comp.propOrder = 'name';
await comp.$nextTick();
// THEN
expect(questionServiceStub.retrieve.mock.lastCall?.[0]).toMatchObject({
sort: ['name,asc', 'id'],
});
});
it('Should call delete service on confirmDelete', async () => {
// GIVEN
questionServiceStub.delete.mockResolvedValue({});
// WHEN
comp.prepareRemove({ id: 123 });
comp.removeQuestion();
await comp.$nextTick(); // clear components
// THEN
expect(questionServiceStub.delete).toHaveBeenCalled();
// THEN
await comp.$nextTick(); // handle component clear watch
expect(questionServiceStub.retrieve).toHaveBeenCalledTimes(1);
});
});
});
});
@@ -0,0 +1,134 @@
import { type Ref, defineComponent, inject, onMounted, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useAlertService } from '@/shared/alert/alert.service';
import { type IQuestion } from '@/shared/model/question.model';
import QuestionService from './question.service';
export default defineComponent({
name: 'Question',
setup() {
const { t: t$ } = useI18n();
const questionService = inject('questionService', () => new QuestionService());
const alertService = inject('alertService', () => useAlertService(), true);
const itemsPerPage = ref(20);
const queryCount: Ref<number> = ref(null);
const page: Ref<number> = ref(1);
const propOrder = ref('id');
const reverse = ref(false);
const totalItems = ref(0);
const questions: Ref<IQuestion[]> = ref([]);
const isFetching = ref(false);
const clear = () => {
page.value = 1;
};
const sort = (): Array<any> => {
const result = [`${propOrder.value},${reverse.value ? 'desc' : 'asc'}`];
if (propOrder.value !== 'id') {
result.push('id');
}
return result;
};
const retrieveQuestions = async () => {
isFetching.value = true;
try {
const paginationQuery = {
page: page.value - 1,
size: itemsPerPage.value,
sort: sort(),
};
const res = await questionService().retrieve(paginationQuery);
totalItems.value = Number(res.headers['x-total-count']);
queryCount.value = totalItems.value;
questions.value = res.data;
} catch (err) {
alertService.showHttpError(err.response);
} finally {
isFetching.value = false;
}
};
const handleSyncList = () => {
retrieveQuestions();
};
onMounted(async () => {
await retrieveQuestions();
});
const removeId: Ref<number> = ref(null);
const removeEntity = ref<any>(null);
const prepareRemove = (instance: IQuestion) => {
removeId.value = instance.id;
removeEntity.value.show();
};
const closeDialog = () => {
removeEntity.value.hide();
};
const removeQuestion = async () => {
try {
await questionService().delete(removeId.value);
const message = t$('questionBankApp.question.deleted', { param: removeId.value }).toString();
alertService.showInfo(message, { variant: 'danger' });
removeId.value = null;
retrieveQuestions();
closeDialog();
} catch (error) {
alertService.showHttpError(error.response);
}
};
const changeOrder = (newOrder: string) => {
if (propOrder.value === newOrder) {
reverse.value = !reverse.value;
} else {
reverse.value = false;
}
propOrder.value = newOrder;
};
// Whenever order changes, reset the pagination
watch([propOrder, reverse], async () => {
if (page.value === 1) {
// first page, retrieve new data
await retrieveQuestions();
} else {
// reset the pagination
clear();
}
});
// Whenever page changes, switch to the new page.
watch(page, async () => {
await retrieveQuestions();
});
return {
questions,
handleSyncList,
isFetching,
retrieveQuestions,
clear,
removeId,
removeEntity,
prepareRemove,
closeDialog,
removeQuestion,
itemsPerPage,
queryCount,
page,
propOrder,
reverse,
totalItems,
changeOrder,
t$,
};
},
});
@@ -0,0 +1,161 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import axios from 'axios';
import { Question } from '@/shared/model/question.model';
import QuestionService from './question.service';
const error = {
response: {
status: null,
data: {
type: null,
},
},
};
const axiosStub = {
get: vi.spyOn(axios, 'get'),
post: vi.spyOn(axios, 'post'),
put: vi.spyOn(axios, 'put'),
patch: vi.spyOn(axios, 'patch'),
delete: vi.spyOn(axios, 'delete'),
};
describe('Service Tests', () => {
describe('Question Service', () => {
let service: QuestionService;
let elemDefault;
beforeEach(() => {
service = new QuestionService();
elemDefault = new Question(123, 'AAAAAAA', 'AAAAAAA', false);
});
describe('Service methods', () => {
it('should find an element', async () => {
const returnedFromService = { ...elemDefault };
axiosStub.get.mockResolvedValue({ data: returnedFromService });
return service.find(123).then(res => {
expect(res).toMatchObject(elemDefault);
});
});
it('should not find an element', async () => {
axiosStub.get.mockRejectedValue(error);
return service
.find(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should create a Question', async () => {
const returnedFromService = { id: 123, ...elemDefault };
const expected = { ...returnedFromService };
axiosStub.post.mockResolvedValue({ data: returnedFromService });
return service.create({}).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not create a Question', async () => {
axiosStub.post.mockRejectedValue(error);
return service
.create({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should update a Question', async () => {
const returnedFromService = { prompt: 'BBBBBB', explanation: 'BBBBBB', active: true, ...elemDefault };
const expected = { ...returnedFromService };
axiosStub.put.mockResolvedValue({ data: returnedFromService });
return service.update(expected).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not update a Question', async () => {
axiosStub.put.mockRejectedValue(error);
return service
.update({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should partial update a Question', async () => {
const patchObject = { active: true, ...new Question() };
const returnedFromService = Object.assign(patchObject, elemDefault);
const expected = { ...returnedFromService };
axiosStub.patch.mockResolvedValue({ data: returnedFromService });
return service.partialUpdate(patchObject).then(res => {
expect(res).toMatchObject(expected);
});
});
it('should not partial update a Question', async () => {
axiosStub.patch.mockRejectedValue(error);
return service
.partialUpdate({})
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should return a list of Question', async () => {
const returnedFromService = { prompt: 'BBBBBB', explanation: 'BBBBBB', active: true, ...elemDefault };
const expected = { ...returnedFromService };
axiosStub.get.mockResolvedValue([returnedFromService]);
return service.retrieve({ sort: {}, page: 0, size: 10 }).then(res => {
expect(res).toContainEqual(expected);
});
});
it('should not return a list of Question', async () => {
axiosStub.get.mockRejectedValue(error);
return service
.retrieve()
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
it('should delete a Question', async () => {
axiosStub.delete.mockResolvedValue({ ok: true });
return service.delete(123).then(res => {
expect(res.ok).toBeTruthy();
});
});
it('should not delete a Question', async () => {
axiosStub.delete.mockRejectedValue(error);
return service
.delete(123)
.then()
.catch(err => {
expect(err).toMatchObject(error);
});
});
});
});
});
@@ -0,0 +1,86 @@
import axios from 'axios';
import { type IQuestion } from '@/shared/model/question.model';
import buildPaginationQueryOpts from '@/shared/sort/sorts';
const baseApiUrl = 'api/questions';
export default class QuestionService {
find(id: number): Promise<IQuestion> {
return new Promise<IQuestion>((resolve, reject) => {
axios
.get(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
retrieve(paginationQuery?: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.get(`${baseApiUrl}?${buildPaginationQueryOpts(paginationQuery)}`)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
delete(id: number): Promise<any> {
return new Promise<any>((resolve, reject) => {
axios
.delete(`${baseApiUrl}/${id}`)
.then(res => {
resolve(res);
})
.catch(err => {
reject(err);
});
});
}
create(entity: IQuestion): Promise<IQuestion> {
return new Promise<IQuestion>((resolve, reject) => {
axios
.post(baseApiUrl, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
update(entity: IQuestion): Promise<IQuestion> {
return new Promise<IQuestion>((resolve, reject) => {
axios
.put(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
partialUpdate(entity: IQuestion): Promise<IQuestion> {
return new Promise<IQuestion>((resolve, reject) => {
axios
.patch(`${baseApiUrl}/${entity.id}`, entity)
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(err);
});
});
}
}
@@ -0,0 +1,126 @@
<template>
<div>
<h2 id="page-heading" data-cy="QuestionHeading">
<span id="question">{{ t$('questionBankApp.question.home.title') }}</span>
<div class="d-flex justify-content-end">
<button class="btn btn-info me-2" @click="handleSyncList" :disabled="isFetching">
<font-awesome-icon icon="sync" :spin="isFetching"></font-awesome-icon>
<span>{{ t$('questionBankApp.question.home.refreshListLabel') }}</span>
</button>
<router-link :to="{ name: 'QuestionCreate' }" custom v-slot="{ navigate }">
<button
@click="navigate"
id="jh-create-entity"
data-cy="entityCreateButton"
class="btn btn-primary jh-create-entity create-question"
>
<font-awesome-icon icon="plus"></font-awesome-icon>
<span>{{ t$('questionBankApp.question.home.createLabel') }}</span>
</button>
</router-link>
</div>
</h2>
<br />
<div class="alert alert-warning" v-if="!isFetching && questions?.length === 0">
<span>{{ t$('questionBankApp.question.home.notFound') }}</span>
</div>
<div class="table-responsive" v-if="questions?.length > 0">
<table class="table table-striped" aria-describedby="questions">
<thead>
<tr>
<th scope="col" @click="changeOrder('id')">
<span>{{ t$('global.field.id') }}</span>
<jhi-sort-indicator :current-order="propOrder" :reverse="reverse" :field-name="'id'"></jhi-sort-indicator>
</th>
<th scope="col" @click="changeOrder('prompt')">
<span>{{ t$('questionBankApp.question.prompt') }}</span>
<jhi-sort-indicator :current-order="propOrder" :reverse="reverse" :field-name="'prompt'"></jhi-sort-indicator>
</th>
<th scope="col" @click="changeOrder('explanation')">
<span>{{ t$('questionBankApp.question.explanation') }}</span>
<jhi-sort-indicator :current-order="propOrder" :reverse="reverse" :field-name="'explanation'"></jhi-sort-indicator>
</th>
<th scope="col" @click="changeOrder('active')">
<span>{{ t$('questionBankApp.question.active') }}</span>
<jhi-sort-indicator :current-order="propOrder" :reverse="reverse" :field-name="'active'"></jhi-sort-indicator>
</th>
<th scope="col" @click="changeOrder('subject.name')">
<span>{{ t$('questionBankApp.question.subject') }}</span>
<jhi-sort-indicator :current-order="propOrder" :reverse="reverse" :field-name="'subject.name'"></jhi-sort-indicator>
</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="question in questions" :key="question.id" data-cy="entityTable">
<td>
<router-link :to="{ name: 'QuestionView', params: { questionId: question.id } }">{{ question.id }}</router-link>
</td>
<td>{{ question.prompt }}</td>
<td>{{ question.explanation }}</td>
<td>{{ question.active }}</td>
<td>
<div v-if="question.subject">
<router-link :to="{ name: 'SubjectView', params: { subjectId: question.subject.id } }">{{
question.subject.name
}}</router-link>
</div>
</td>
<td class="text-end">
<div class="btn-group">
<router-link :to="{ name: 'QuestionView', params: { questionId: question.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-info btn-sm details" data-cy="entityDetailsButton">
<font-awesome-icon icon="eye"></font-awesome-icon>
<span class="d-none d-md-inline">{{ t$('entity.action.view') }}</span>
</button>
</router-link>
<router-link :to="{ name: 'QuestionEdit', params: { questionId: question.id } }" custom v-slot="{ navigate }">
<button @click="navigate" class="btn btn-primary btn-sm edit" data-cy="entityEditButton">
<font-awesome-icon icon="pencil-alt"></font-awesome-icon>
<span class="d-none d-md-inline">{{ t$('entity.action.edit') }}</span>
</button>
</router-link>
<b-button @click="prepareRemove(question)" variant="danger" class="btn btn-sm" data-cy="entityDeleteButton">
<font-awesome-icon icon="times"></font-awesome-icon>
<span class="d-none d-md-inline">{{ t$('entity.action.delete') }}</span>
</b-button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<b-modal ref="removeEntity" id="removeEntity">
<template #title>
<span id="questionBankApp.question.delete.question" data-cy="questionDeleteDialogHeading">{{ t$('entity.delete.title') }}</span>
</template>
<div class="modal-body">
<p id="jhi-delete-question-heading">{{ t$('questionBankApp.question.delete.question', { id: removeId }) }}</p>
</div>
<template #footer>
<div>
<button type="button" class="btn btn-secondary" @click="closeDialog()">{{ t$('entity.action.cancel') }}</button>
<button
type="button"
class="btn btn-primary"
id="jhi-confirm-delete-question"
data-cy="entityConfirmDeleteButton"
@click="removeQuestion"
>
{{ t$('entity.action.delete') }}
</button>
</div>
</template>
</b-modal>
<div v-show="questions?.length > 0">
<div class="d-flex justify-content-center">
<jhi-item-count :page="page" :total="queryCount" :items-per-page="itemsPerPage"></jhi-item-count>
</div>
<div class="d-flex justify-content-center">
<b-pagination size="md" :total-rows="totalItems" v-model="page" :per-page="itemsPerPage"></b-pagination>
</div>
</div>
</div>
</template>
<script lang="ts" src="./question.component.ts"></script>