Skip to content

Commit

Permalink
Add front-end test
Browse files Browse the repository at this point in the history
  • Loading branch information
felder101 committed Jan 7, 2025
1 parent 3a526df commit 569fc2e
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 4 deletions.
2 changes: 1 addition & 1 deletion training-front-end/src/components/AdminTrainingReport.vue
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
//format dates from uswds standard to the format needed for backend
const formatDateToYYYYMMDD = (dates) => {
return dates ? dates.map(date => (date ? new Date(date).toISOString().split('T')[0] : null)) : [];
return dates ? dates.map(date => (date ? new Date(date).toISOString() : null)) : [];
};
async function downloadReport() {
Expand Down
6 changes: 3 additions & 3 deletions training-front-end/src/components/TrainingReportDownload.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script setup>
import {computed, reactive, ref, watch} from "vue"
import { computed, reactive, ref, watch} from "vue"
import { useStore } from '@nanostores/vue'
import { useVuelidate } from "@vuelidate/core";
import { profile } from '../stores/user'
Expand All @@ -10,7 +10,7 @@ import USWDSComboBox from "./form-components/USWDSComboBox.vue";
import {agencyList, bureauList, setSelectedAgencyId} from "../stores/agencies.js";
import ReportRepository from "./ReportRepository.vue";
import ReportUtilities from "./ReportUtilities.vue";
import SpinnerGraphic from "@components/SpinnerGraphic.vue";
import SpinnerGraphic from "./SpinnerGraphic.vue";
const error = ref()
const showSuccessMessage = ref(false)
Expand Down Expand Up @@ -68,7 +68,7 @@ const v_all_info$ = useVuelidate(validation_info, user_input)
//format dates from uswds standard to the format needed for backend
const formatDateToYYYYMMDD = (dates) => {
return dates ? dates.map(date => (date ? new Date(date).toISOString().split('T')[0] : null)) : [];
return dates ? dates.map(date => (date ? new Date(date).toISOString() : null)) : [];
};
async function downloadReport() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { mount, flushPromises } from '@vue/test-utils'
import { vi } from 'vitest';
import TrainingReportDownload from '../TrainingReportDownload.vue';
import ReportRepository from '../ReportRepository.vue';
import { profile } from '../../stores/user';

// Mocking the ReportUtilities module
vi.mock('../ReportUtilities.vue', () => ({
default: {
downloadBlobAsFile: vi.fn(), // Mock this method to do nothing
},
}));

const agency_api = [
{ 'id': 1, 'name': 'General Services Administration', 'bureaus': []},
{ 'id': 2,
'name': 'Department of the Treasury',
'bureaus': [
{'id': 3, 'name': 'United States Mint'},
{'id': 4, 'name': 'Financial Crimes Enforcement'}
]
},
{ 'id': 5, 'name': 'Department of the Interior', 'bureaus': []}
]

describe('TrainingReportDownload.vue', () => {
let wrapper;

beforeEach(async () => {
// Reset all mocks before each test
vi.clearAllMocks();

vi.spyOn(global, 'fetch').mockImplementation(() => {
return Promise.resolve({ok: true, status:200, json: () => Promise.resolve(agency_api) })
})

// Set the profile mock with Report role
profile.set({ name: 'Amelia Sedley', jwt: 'some-token-value', roles: ['Report'],
report_agencies: [
{name: 'General Services Administration', bureau: null, id: 1},
{name: 'Department of the Treasury', bureau: 'Financial Crimes Enforcement', id: 4},
{name: 'Department of the Interior', bureau: null, id: 5}
] });

wrapper = await mount(TrainingReportDownload, {
global: {
stubs: {
// Stub child components that are not essential for the test
USWDSAlert: true,
ValidatedSelect: true,
ValidatedDateRangePicker: true,
ValidatedCheckboxGroup: true,
SpinnerGraphic: true,
},
},
});
});

it('renders the form when the user is an Report', () => {
expect(wrapper.html()).toContain('Enter Report Parameters');
expect(wrapper.find('form').exists()).toBe(true);
});

it('displays an error message when the user is not authorized', async () => {
// Change the profile to non report user
profile.set({ name: 'Amelia Sedley', jwt: 'some-token-value', roles: [] });

await wrapper.vm.$nextTick();

expect(wrapper.html()).toContain('You are not authorized to receive reports.');
expect(wrapper.find('form').exists()).toBe(false);
});

it('handles errors during report download', async () => {
ReportRepository.downloadTrainingCompletionReport = vi.fn(() => Promise.reject(new Error('Failed to download')));

await wrapper.find('form').trigger('submit.prevent');

expect(wrapper.vm.error.message).toBe('Failed to download');
});

it('shows a success message after a successful report download', async () => {
ReportRepository.downloadTrainingCompletionReport = vi.fn(() =>
Promise.resolve({
blob: () => new Blob(['mock-csv-content'], { type: 'text/csv' }),
})
);

// Trigger the form submission
await wrapper.find('form').trigger('submit.prevent');

// Wait for all pending promises and Vue updates to complete
await flushPromises();

// Assert that the success message is shown
expect(wrapper.vm.showSuccessMessage).toBe(true);
});

it('displays a spinner while the report is loading', async () => {
const downloadPromise = new Promise(() => {}); // Mock a pending download
ReportRepository.downloadTrainingCompletionReport = vi.fn(() => downloadPromise);

await wrapper.find('form').trigger('submit.prevent');

expect(wrapper.vm.showSpinner).toBe(true);
});
});

0 comments on commit 569fc2e

Please sign in to comment.