Files
iot-dc3/dc3-web/tests/unit/use-entity-names.test.ts
pnokerandClaude Code 3fb43c4239 feat(web): unify three-terminal control density and close audit defects
Land the v7 three-terminal UX decision: drop the width/pointer-based
44px touch enlargement so one 32px density holds across desktop,
tablet, and mobile, and rebuild entity pages on a responsive record
list (ResponsiveRecordList + EntityMobileCard + per-entity mobile
summaries). Tighten the nginx security headers (CSP frame-ancestors
'none', X-Frame-Options DENY) to match the static e2e server.

Complete the dc3-web audit remediation, including the remaining LOW
items from docs/dc3-web-low-defects-handoff.md: streaming-safe
message loads in the agentic store, mock menu reparent cycle
rejection, paged-list page clamping, fetch/axios mock request
normalization, per-table attribute catalogs, post-flush alarm
watchers, rowKey-agnostic delete state, localized card text
fallbacks, and e2e-server port fail-fast.

Gate: vue-tsc, eslint, vitest 687 passed, responsive e2e 64 passed.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-07 19:33:17 +08:00

219 lines
8.1 KiB
TypeScript

/*
* Copyright 2016-present the IoT DC3 original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {beforeEach, describe, expect, it, vi} from 'vitest';
const apiMocks = vi.hoisted(() => ({
listDeviceByIds: vi.fn(),
listDriverByIds: vi.fn(),
listProfileByIds: vi.fn(),
listPointByIds: vi.fn(),
}));
vi.mock('@/api/device', () => ({listDeviceByIds: apiMocks.listDeviceByIds}));
vi.mock('@/api/driver', () => ({listDriverByIds: apiMocks.listDriverByIds}));
vi.mock('@/api/profile', () => ({listProfileByIds: apiMocks.listProfileByIds}));
vi.mock('@/api/point', () => ({listPointByIds: apiMocks.listPointByIds}));
// Module under test imports the mocked APIs at module scope, so we must
// import it AFTER vi.mock — but the cache is module-level, so each test
// file resets through vi.resetModules() in beforeEach to keep tests
// independent.
async function loadHook() {
const mod = await import('@/composables/useEntityNames');
return mod.useEntityNames();
}
describe('useEntityNames', () => {
beforeEach(async () => {
vi.clearAllMocks();
// Reset the module so the in-module reactive cache is empty at the
// start of each test — otherwise the cache leaks between tests.
vi.resetModules();
apiMocks.listDeviceByIds.mockResolvedValue({'d-1': {deviceName: 'Boiler'}, 'd-2': {deviceName: 'Compressor'}});
apiMocks.listDriverByIds.mockResolvedValue({'drv-1': {driverName: 'Modbus'}});
apiMocks.listProfileByIds.mockResolvedValue({'p-1': {profileName: 'TempSensor'}});
apiMocks.listPointByIds.mockResolvedValue({'pt-1': {pointName: 'Inlet temperature'}});
});
it('falls back to the id when the cache is cold and resolves names after fetching', async () => {
const hook = await loadHook();
// Cold cache → display name falls back to the id string.
expect(hook.deviceName('d-1')).toBe('d-1');
await hook.resolveDevices(['d-1', 'd-2']);
expect(apiMocks.listDeviceByIds).toHaveBeenCalledTimes(1);
expect(apiMocks.listDeviceByIds).toHaveBeenCalledWith(['d-1', 'd-2']);
expect(hook.deviceName('d-1')).toBe('Boiler');
expect(hook.deviceName('d-2')).toBe('Compressor');
});
it('coerces null/undefined ids to empty string instead of throwing', async () => {
const hook = await loadHook();
expect(hook.deviceName(null)).toBe('');
expect(hook.deviceName(undefined)).toBe('');
expect(hook.driverName(null)).toBe('');
expect(hook.profileName(null)).toBe('');
expect(hook.pointName(null)).toBe('');
});
it('coerces numeric ids to strings before lookup', async () => {
apiMocks.listDeviceByIds.mockResolvedValueOnce({'42': {deviceName: 'Mixer'}});
const hook = await loadHook();
await hook.resolveDevices([42]);
expect(apiMocks.listDeviceByIds).toHaveBeenCalledWith(['42']);
expect(hook.deviceName(42)).toBe('Mixer');
});
it('does not refetch ids that are already cached', async () => {
const hook = await loadHook();
await hook.resolveDevices(['d-1']);
await hook.resolveDevices(['d-1']);
await hook.resolveDevices(['d-1']);
// Only the first call hits the API; subsequent calls are served from cache.
expect(apiMocks.listDeviceByIds).toHaveBeenCalledTimes(1);
});
it('caches the id itself when the backend returns no name (deleted entity)', async () => {
apiMocks.listDriverByIds.mockResolvedValueOnce({});
const hook = await loadHook();
await hook.resolveDrivers(['drv-missing']);
// Cache contains the id-as-name fallback, so subsequent calls see a
// truthy hit and do NOT re-issue the request — we don't want to keep
// re-fetching deleted entities every time a historical row references them.
expect(hook.driverName('drv-missing')).toBe('drv-missing');
await hook.resolveDrivers(['drv-missing']);
expect(apiMocks.listDriverByIds).toHaveBeenCalledTimes(1);
});
it('swallows API errors silently — UI falls back to the id', async () => {
apiMocks.listProfileByIds.mockRejectedValueOnce(new Error('500'));
const hook = await loadHook();
// Must not throw — global axios interceptor surfaces the error toast.
await expect(hook.resolveProfiles(['p-err'])).resolves.toBeUndefined();
expect(hook.profileName('p-err')).toBe('p-err');
});
it('dedupes inflight requests when the same ids are resolved concurrently', async () => {
let resolveFetch!: (value: unknown) => void;
apiMocks.listDeviceByIds.mockReturnValueOnce(
new Promise((resolve) => {
resolveFetch = resolve;
})
);
const hook = await loadHook();
// Two concurrent resolveDevices calls for the same ids — only one HTTP
// request should fire because the second sees the ids in inflight.
const first = hook.resolveDevices(['d-1']);
const second = hook.resolveDevices(['d-1']);
resolveFetch({'d-1': {deviceName: 'Boiler'}});
await Promise.all([first, second]);
expect(apiMocks.listDeviceByIds).toHaveBeenCalledTimes(1);
expect(hook.deviceName('d-1')).toBe('Boiler');
});
it('waits for the matching batch when disjoint requests overlap', async () => {
let resolveFirst!: (value: unknown) => void;
let resolveSecond!: (value: unknown) => void;
apiMocks.listDeviceByIds.mockImplementation((ids: string[]) => {
if (ids[0] === 'd-1') {
return new Promise((resolve) => {
resolveFirst = resolve;
});
}
return new Promise((resolve) => {
resolveSecond = resolve;
});
});
const hook = await loadHook();
const first = hook.resolveDevices(['d-1']);
const second = hook.resolveDevices(['d-2']);
let thirdSettled = false;
const third = hook.resolveDevices(['d-2']).then(() => {
thirdSettled = true;
});
await Promise.resolve();
expect(apiMocks.listDeviceByIds).toHaveBeenCalledTimes(2);
expect(thirdSettled).toBe(false);
resolveFirst({'d-1': {deviceName: 'Boiler'}});
resolveSecond({'d-2': {deviceName: 'Compressor'}});
await Promise.all([first, second, third]);
expect(thirdSettled).toBe(true);
expect(hook.deviceName('d-2')).toBe('Compressor');
});
it('resolveBySource splits device/driver ids into a single batched fetch each', async () => {
const hook = await loadHook();
await hook.resolveBySource([
{source: 'device', sourceId: 'd-1'},
{source: 'driver', sourceId: 'drv-1'},
{source: 'device', sourceId: 'd-2'},
]);
expect(apiMocks.listDeviceByIds).toHaveBeenCalledTimes(1);
expect(apiMocks.listDeviceByIds).toHaveBeenCalledWith(['d-1', 'd-2']);
expect(apiMocks.listDriverByIds).toHaveBeenCalledTimes(1);
expect(apiMocks.listDriverByIds).toHaveBeenCalledWith(['drv-1']);
});
it('nameBySource routes to deviceName / driverName by source', async () => {
const hook = await loadHook();
await hook.resolveBySource([
{source: 'device', sourceId: 'd-1'},
{source: 'driver', sourceId: 'drv-1'},
]);
expect(hook.nameBySource('device', 'd-1')).toBe('Boiler');
expect(hook.nameBySource('driver', 'drv-1')).toBe('Modbus');
});
it('handles empty input arrays without firing any request', async () => {
const hook = await loadHook();
await hook.resolveDevices([]);
await hook.resolveDrivers([]);
await hook.resolveProfiles([]);
await hook.resolvePoints([]);
expect(apiMocks.listDeviceByIds).not.toHaveBeenCalled();
expect(apiMocks.listDriverByIds).not.toHaveBeenCalled();
expect(apiMocks.listProfileByIds).not.toHaveBeenCalled();
expect(apiMocks.listPointByIds).not.toHaveBeenCalled();
});
});