Files
magistr/frontend/tests/browser/study-plans.test.mjs
T

251 lines
9.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import assert from 'node:assert/strict';
import { after, before, test } from 'node:test';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { build } from 'esbuild';
import { chromium } from 'playwright';
let browser, server, origin, bundle, styles;
const metadata = {
profiles: [
{ id: 1, name: 'Программная инженерия', specialtyCode: '09.03.01' },
],
educationForms: [{ id: 1, name: 'Бакалавриат' }],
semesters: [
{
id: 1,
name: '2026–2027 · Осень',
startYear: 2026,
semesterType: 'autumn',
},
],
groups: [
{
id: 1,
name: 'ИВТ-21-1',
specialtyProfileId: 1,
educationFormId: 1,
yearStartStudy: 2025,
},
],
subjects: [
{ id: 1, name: 'Операционные системы', code: 'ОС', departmentId: 1 },
],
};
function initialDetails() {
return {
plan: {
id: 1,
title: 'План третьего семестра',
specialtyProfileId: 1,
profileName: 'Программная инженерия',
specialtyCode: '09.03.01',
educationFormId: 1,
educationFormName: 'Бакалавриат',
semesterNumber: 3,
revision: 0,
},
subjects: [
{
subjectId: 1,
name: 'Операционные системы',
code: 'ОС',
departmentId: 1,
loads: ['LECTURE', 'PRACTICE', 'LABORATORY'].map(
(category, i) => ({
category,
academicHours: i === 2 ? 18 : 36,
splitSubgroups: false,
teacherId: 7,
teacherName: 'Иванов И. И.',
workloadHours: i === 2 ? 18 : 36,
}),
),
academicHours: 90,
workloadHours: 90,
},
],
assignments: [],
};
}
before(async () => {
bundle = (
await build({
stdin: {
contents: `import React from 'react'; import { createRoot } from 'react-dom/client'; import { storeAuthState } from './auth-session.js'; import { StudyPlansTab } from './react/admin/tabs/StudyPlansTab.jsx'; storeAuthState({ token: 'test-token', role: window.testRole || 'ADMIN', userId: 1, departmentId: 1 }); createRoot(document.getElementById('root')).render(<StudyPlansTab />);`,
resolveDir: process.cwd(),
loader: 'jsx',
},
bundle: true,
write: false,
format: 'iife',
jsx: 'automatic',
define: { 'process.env.NODE_ENV': '"test"' },
})
).outputFiles[0].text;
styles = (
await Promise.all(
['admin/css/main.css', 'admin/css/components.css'].map((p) =>
readFile(p, 'utf8'),
),
)
).join('\n');
server = createServer((req, res) => {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('<div id="root"></div>');
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
origin = `http://127.0.0.1:${server.address().port}`;
browser = await chromium.launch({
executablePath: process.env.CHROMIUM_PATH || '/usr/bin/chromium',
});
});
after(async () => {
await browser?.close();
if (server)
await new Promise((resolve) => {
server.closeAllConnections();
server.close(resolve);
});
});
async function fixture(t, role = 'ADMIN') {
const page = await browser.newPage({
viewport: { width: 1440, height: 1100 },
});
const errors = [],
writes = [];
let details = initialDetails();
page.on('pageerror', (error) => errors.push(error.stack));
await page.route(/\/api\/study-plans/, async (route) => {
const request = route.request(),
url = new URL(request.url());
let response;
if (url.pathname.endsWith('/metadata')) response = metadata;
else if (url.pathname.endsWith('/teacher-options'))
response = [{ id: 7, fullName: 'Иванов И. И.' }];
else if (
request.method() === 'PUT' &&
url.pathname.endsWith('/subjects/1')
) {
const body = request.postDataJSON();
writes.push(body);
details.plan.revision++;
details.subjects[0].loads = body.loads.map((l) => ({
...l,
teacherName: 'Иванов И. И.',
workloadHours: l.academicHours * (l.splitSubgroups ? 2 : 1),
}));
details.subjects[0].workloadHours =
details.subjects[0].loads.reduce(
(sum, l) => sum + l.workloadHours,
0,
);
response = details;
} else if (
request.method() === 'POST' &&
url.pathname.endsWith('/assignments')
) {
writes.push(request.postDataJSON());
details.assignments = [
{
groupId: 1,
groupName: 'ИВТ-21-1',
semesterId: 1,
semesterTitle: metadata.semesters[0].name,
},
];
response = details;
} else
response =
url.pathname === '/api/study-plans' ? [details.plan] : details;
await route.fulfill({ json: response });
});
await page.goto(origin);
await page.addStyleTag({ content: styles });
await page.evaluate((role) => {
window.testRole = role;
}, role);
await page.addScriptTag({ content: bundle });
await page
.locator('select')
.first()
.selectOption('1', { force: true, timeout: 5000 });
await page.getByRole('heading', { name: 'Дисциплины и часы' }).waitFor();
t.after(async () => {
await page.close();
assert.deepEqual(errors, []);
});
return { page, writes };
}
test('редактор удваивает только лабораторную нагрузку, сохраняя учебные часы', async (t) => {
const { page, writes } = await fixture(t);
await page.getByRole('button', { name: 'Изменить', exact: true }).click();
assert.equal(await page.getByRole('checkbox').count(), 1);
await page.locator('label.checkbox-item').click();
assert.ok(
await page
.getByRole('checkbox', { name: 'Делить на две подгруппы' })
.isChecked(),
);
await page
.locator('.study-plan-load-card')
.last()
.getByText('36 ч', { exact: true })
.waitFor();
await page.getByRole('button', { name: 'Сохранить дисциплину' }).click();
await page
.getByRole('status')
.filter({ hasText: 'Дисциплина и нагрузка сохранены' })
.waitFor();
assert.equal(writes[0].loads[2].academicHours, 18);
assert.equal(writes[0].loads[2].splitSubgroups, true);
assert.equal(writes[0].loads[0].splitSubgroups, false);
assert.equal(
await page.locator('.study-plan-totals strong').last().textContent(),
'108',
);
await page.waitForTimeout(400);
await page.screenshot({
path: '/tmp/magistr-study-plans.png',
fullPage: true,
});
await page.setViewportSize({ width: 390, height: 844 });
assert.equal(
await page
.locator('.study-plan-load-grid')
.evaluate(
(el) =>
getComputedStyle(el).gridTemplateColumns.split(' ').length,
),
1,
);
});
test('совместимая группа закрепляется за календарным семестром', async (t) => {
const { page, writes } = await fixture(t),
form = page.locator('form').last();
await form.locator('select').first().selectOption('1', { force: true });
await form.locator('select').last().selectOption('1', { force: true });
await form.getByRole('button', { name: 'Закрепить план' }).click();
await page
.getByRole('status')
.filter({ hasText: 'План закреплён за группой' })
.waitFor();
assert.deepEqual(writes[0], { groupId: 1, semesterId: 1 });
await page.getByRole('cell', { name: 'ИВТ-21-1', exact: true }).waitFor();
});
test('кафедра читает план без форм изменения', async (t) => {
const { page } = await fixture(t, 'DEPARTMENT');
assert.equal(
await page
.getByRole('button', { name: 'Сохранить дисциплину' })
.count(),
0,
);
assert.equal(
await page.getByRole('button', { name: 'Закрепить план' }).count(),
0,
);
assert.ok(
(await page.getByText('Иванов И. И.', { exact: true }).count()) > 0,
);
});