Apply repository-wide ESLint auto-fix formatting pass
Co-Authored-By: Codex <codex@openai.com>
This commit is contained in:
@@ -3,29 +3,29 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import Badge from '@/components/Badge.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import Badge from "@/components/Badge.vue";
|
||||
|
||||
describe('Badge', () => {
|
||||
it('renders display text', () => {
|
||||
describe("Badge", () => {
|
||||
it("renders display text", () => {
|
||||
const wrapper = mount(Badge, {
|
||||
props: { isActivated: true, displayText: 'Active' },
|
||||
props: { isActivated: true, displayText: "Active" },
|
||||
});
|
||||
expect(wrapper.text()).toBe('Active');
|
||||
expect(wrapper.text()).toBe("Active");
|
||||
});
|
||||
|
||||
it('has activated class when isActivated is true', () => {
|
||||
it("has activated class when isActivated is true", () => {
|
||||
const wrapper = mount(Badge, {
|
||||
props: { isActivated: true, displayText: 'Active' },
|
||||
props: { isActivated: true, displayText: "Active" },
|
||||
});
|
||||
expect(wrapper.classes()).toContain('badge-activated');
|
||||
expect(wrapper.classes()).toContain("badge-activated");
|
||||
});
|
||||
|
||||
it('has deactivated class when isActivated is false', () => {
|
||||
it("has deactivated class when isActivated is false", () => {
|
||||
const wrapper = mount(Badge, {
|
||||
props: { isActivated: false, displayText: 'Inactive' },
|
||||
props: { isActivated: false, displayText: "Inactive" },
|
||||
});
|
||||
expect(wrapper.classes()).toContain('badge-deactivated');
|
||||
expect(wrapper.classes()).toContain("badge-deactivated");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,32 +3,32 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import Button from '@/components/Button.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import Button from "@/components/Button.vue";
|
||||
|
||||
describe('Button', () => {
|
||||
it('renders button text', () => {
|
||||
describe("Button", () => {
|
||||
it("renders button text", () => {
|
||||
const wrapper = mount(Button, {
|
||||
props: { buttonText: 'Click Me' },
|
||||
props: { buttonText: "Click Me" },
|
||||
});
|
||||
expect(wrapper.text()).toBe('Click Me');
|
||||
expect(wrapper.text()).toBe("Click Me");
|
||||
});
|
||||
|
||||
it('adds ring classes on mousedown', async () => {
|
||||
it("adds ring classes on mousedown", async () => {
|
||||
const wrapper = mount(Button, {
|
||||
props: { buttonText: 'Test' },
|
||||
props: { buttonText: "Test" },
|
||||
});
|
||||
await wrapper.trigger('mousedown');
|
||||
expect(wrapper.classes()).toContain('ring');
|
||||
await wrapper.trigger("mousedown");
|
||||
expect(wrapper.classes()).toContain("ring");
|
||||
});
|
||||
|
||||
it('removes ring classes on mouseup', async () => {
|
||||
it("removes ring classes on mouseup", async () => {
|
||||
const wrapper = mount(Button, {
|
||||
props: { buttonText: 'Test' },
|
||||
props: { buttonText: "Test" },
|
||||
});
|
||||
await wrapper.trigger('mousedown');
|
||||
await wrapper.trigger('mouseup');
|
||||
expect(wrapper.classes()).not.toContain('ring');
|
||||
await wrapper.trigger("mousedown");
|
||||
await wrapper.trigger("mouseup");
|
||||
expect(wrapper.classes()).not.toContain("ring");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,32 +3,32 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import ButtonFilled from '@/components/ButtonFilled.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ButtonFilled from "@/components/ButtonFilled.vue";
|
||||
|
||||
describe('ButtonFilled', () => {
|
||||
it('renders button text', () => {
|
||||
describe("ButtonFilled", () => {
|
||||
it("renders button text", () => {
|
||||
const wrapper = mount(ButtonFilled, {
|
||||
props: { buttonText: 'Save' },
|
||||
props: { buttonText: "Save" },
|
||||
});
|
||||
expect(wrapper.text()).toBe('Save');
|
||||
expect(wrapper.text()).toBe("Save");
|
||||
});
|
||||
|
||||
it('has filled background class', () => {
|
||||
it("has filled background class", () => {
|
||||
const wrapper = mount(ButtonFilled, {
|
||||
props: { buttonText: 'Save' },
|
||||
props: { buttonText: "Save" },
|
||||
});
|
||||
expect(wrapper.find('button').exists()).toBe(true);
|
||||
expect(wrapper.find("button").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('adds ring on mousedown and removes on mouseup', async () => {
|
||||
it("adds ring on mousedown and removes on mouseup", async () => {
|
||||
const wrapper = mount(ButtonFilled, {
|
||||
props: { buttonText: 'Test' },
|
||||
props: { buttonText: "Test" },
|
||||
});
|
||||
await wrapper.trigger('mousedown');
|
||||
expect(wrapper.classes()).toContain('ring');
|
||||
await wrapper.trigger('mouseup');
|
||||
expect(wrapper.classes()).not.toContain('ring');
|
||||
await wrapper.trigger("mousedown");
|
||||
expect(wrapper.classes()).toContain("ring");
|
||||
await wrapper.trigger("mouseup");
|
||||
expect(wrapper.classes()).not.toContain("ring");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import IconChecked from '@/components/icons/IconChecked.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import IconChecked from "@/components/icons/IconChecked.vue";
|
||||
|
||||
describe('IconChecked', () => {
|
||||
it('shows gray frame when not checked', () => {
|
||||
describe("IconChecked", () => {
|
||||
it("shows gray frame when not checked", () => {
|
||||
const wrapper = mount(IconChecked, {
|
||||
props: { isChecked: false },
|
||||
});
|
||||
@@ -17,7 +17,7 @@ describe('IconChecked', () => {
|
||||
expect(imgs.length).toBe(1);
|
||||
});
|
||||
|
||||
it('shows blue frame and check mark when checked', () => {
|
||||
it("shows blue frame and check mark when checked", () => {
|
||||
const wrapper = mount(IconChecked, {
|
||||
props: { isChecked: true },
|
||||
});
|
||||
@@ -26,7 +26,7 @@ describe('IconChecked', () => {
|
||||
expect(imgs.length).toBe(2);
|
||||
});
|
||||
|
||||
it('updates rendering when isChecked prop changes', async () => {
|
||||
it("updates rendering when isChecked prop changes", async () => {
|
||||
const wrapper = mount(IconChecked, {
|
||||
props: { isChecked: false },
|
||||
});
|
||||
|
||||
@@ -3,19 +3,19 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import Loading from '@/components/Loading.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import Loading from "@/components/Loading.vue";
|
||||
|
||||
describe('Loading', () => {
|
||||
it('renders a loader element', () => {
|
||||
describe("Loading", () => {
|
||||
it("renders a loader element", () => {
|
||||
const wrapper = mount(Loading);
|
||||
expect(wrapper.find('.loader').exists()).toBe(true);
|
||||
expect(wrapper.find(".loader").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('has full-screen overlay classes', () => {
|
||||
it("has full-screen overlay classes", () => {
|
||||
const wrapper = mount(Loading);
|
||||
expect(wrapper.classes()).toContain('fixed');
|
||||
expect(wrapper.classes()).toContain('inset-0');
|
||||
expect(wrapper.classes()).toContain("fixed");
|
||||
expect(wrapper.classes()).toContain("inset-0");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
@@ -15,14 +15,14 @@ const mockRoute = vi.hoisted(() => ({
|
||||
query: {},
|
||||
}));
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
vi.mock("vue-router", () => ({
|
||||
useRoute: () => mockRoute,
|
||||
}));
|
||||
|
||||
import Login from '@/views/Login/Login.vue';
|
||||
import { useLoginStore } from '@/stores/login';
|
||||
import Login from "@/views/Login/Login.vue";
|
||||
import { useLoginStore } from "@/stores/login";
|
||||
|
||||
describe('Login', () => {
|
||||
describe("Login", () => {
|
||||
let pinia;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -42,62 +42,62 @@ describe('Login', () => {
|
||||
});
|
||||
};
|
||||
|
||||
it('renders login form', () => {
|
||||
it("renders login form", () => {
|
||||
const wrapper = mountLogin();
|
||||
expect(wrapper.find('h2').text()).toBe('LOGIN');
|
||||
expect(wrapper.find('#account').exists()).toBe(true);
|
||||
expect(wrapper.find('#password').exists()).toBe(true);
|
||||
expect(wrapper.find("h2").text()).toBe("LOGIN");
|
||||
expect(wrapper.find("#account").exists()).toBe(true);
|
||||
expect(wrapper.find("#password").exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('has disabled login button when fields are empty', () => {
|
||||
it("has disabled login button when fields are empty", () => {
|
||||
const wrapper = mountLogin();
|
||||
const btn = wrapper.find('#login_btn_main_btn');
|
||||
expect(btn.attributes('disabled')).toBeDefined();
|
||||
const btn = wrapper.find("#login_btn_main_btn");
|
||||
expect(btn.attributes("disabled")).toBeDefined();
|
||||
});
|
||||
|
||||
it('enables login button when both fields have values', async () => {
|
||||
it("enables login button when both fields have values", async () => {
|
||||
const wrapper = mountLogin();
|
||||
const store = useLoginStore();
|
||||
store.auth.username = 'user';
|
||||
store.auth.password = 'pass';
|
||||
store.auth.username = "user";
|
||||
store.auth.password = "pass";
|
||||
await wrapper.vm.$nextTick();
|
||||
const btn = wrapper.find('#login_btn_main_btn');
|
||||
expect(btn.attributes('disabled')).toBeUndefined();
|
||||
const btn = wrapper.find("#login_btn_main_btn");
|
||||
expect(btn.attributes("disabled")).toBeUndefined();
|
||||
});
|
||||
|
||||
it('shows error message when isInvalid', async () => {
|
||||
it("shows error message when isInvalid", async () => {
|
||||
const wrapper = mountLogin();
|
||||
const store = useLoginStore();
|
||||
store.isInvalid = true;
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(wrapper.text()).toContain('Incorrect account or password');
|
||||
expect(wrapper.text()).toContain("Incorrect account or password");
|
||||
});
|
||||
|
||||
it('toggles password visibility', async () => {
|
||||
it("toggles password visibility", async () => {
|
||||
const wrapper = mountLogin();
|
||||
const store = useLoginStore();
|
||||
store.auth.password = 'secret';
|
||||
store.auth.password = "secret";
|
||||
await wrapper.vm.$nextTick();
|
||||
|
||||
const pwdInput = wrapper.find('#password');
|
||||
expect(pwdInput.attributes('type')).toBe('password');
|
||||
const pwdInput = wrapper.find("#password");
|
||||
expect(pwdInput.attributes("type")).toBe("password");
|
||||
|
||||
// Click the eye icon to toggle
|
||||
const eyeToggle = wrapper.find(
|
||||
'label[for="passwordt"] span.cursor-pointer',
|
||||
);
|
||||
if (eyeToggle.exists()) {
|
||||
await eyeToggle.trigger('click');
|
||||
await eyeToggle.trigger("click");
|
||||
await wrapper.vm.$nextTick();
|
||||
expect(pwdInput.attributes('type')).toBe('text');
|
||||
expect(pwdInput.attributes("type")).toBe("text");
|
||||
}
|
||||
});
|
||||
|
||||
it('stores return-to URL from route query', () => {
|
||||
it("stores return-to URL from route query", () => {
|
||||
const wrapper = mountLogin({
|
||||
route: { query: { 'return-to': 'encodedUrl' } },
|
||||
route: { query: { "return-to": "encodedUrl" } },
|
||||
});
|
||||
const store = useLoginStore();
|
||||
expect(store.rememberedReturnToUrl).toBe('encodedUrl');
|
||||
expect(store.rememberedReturnToUrl).toBe("encodedUrl");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import ModalHeader from '@/views/AccountManagement/ModalHeader.vue';
|
||||
import { useModalStore } from '@/stores/modal';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import ModalHeader from "@/views/AccountManagement/ModalHeader.vue";
|
||||
import { useModalStore } from "@/stores/modal";
|
||||
|
||||
describe('ModalHeader', () => {
|
||||
describe("ModalHeader", () => {
|
||||
let pinia;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -17,35 +17,35 @@ describe('ModalHeader', () => {
|
||||
setActivePinia(pinia);
|
||||
});
|
||||
|
||||
const mountModalHeader = (headerText = 'Test Header') => {
|
||||
const mountModalHeader = (headerText = "Test Header") => {
|
||||
return mount(ModalHeader, {
|
||||
props: { headerText },
|
||||
global: { plugins: [pinia] },
|
||||
});
|
||||
};
|
||||
|
||||
it('renders header text from prop', () => {
|
||||
const wrapper = mountModalHeader('Account Info');
|
||||
expect(wrapper.find('h1').text()).toBe('Account Info');
|
||||
it("renders header text from prop", () => {
|
||||
const wrapper = mountModalHeader("Account Info");
|
||||
expect(wrapper.find("h1").text()).toBe("Account Info");
|
||||
});
|
||||
|
||||
it('renders close button (X icon)', () => {
|
||||
it("renders close button (X icon)", () => {
|
||||
const wrapper = mountModalHeader();
|
||||
const img = wrapper.find('img[alt="X"]');
|
||||
expect(img.exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('calls closeModal when X is clicked', async () => {
|
||||
it("calls closeModal when X is clicked", async () => {
|
||||
const wrapper = mountModalHeader();
|
||||
const store = useModalStore();
|
||||
store.isModalOpen = true;
|
||||
store.whichModal = 'SOME_MODAL';
|
||||
store.whichModal = "SOME_MODAL";
|
||||
|
||||
const img = wrapper.find('img[alt="X"]');
|
||||
await img.trigger('click');
|
||||
await img.trigger("click");
|
||||
|
||||
// closeModal only sets isModalOpen to false; whichModal is not reset
|
||||
expect(store.isModalOpen).toBe(false);
|
||||
expect(store.whichModal).toBe('SOME_MODAL');
|
||||
expect(store.whichModal).toBe("SOME_MODAL");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,42 +3,42 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import ResultArrow from '@/components/Discover/Conformance/ConformanceSidebar/ResultArrow.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ResultArrow from "@/components/Discover/Conformance/ConformanceSidebar/ResultArrow.vue";
|
||||
|
||||
describe('ResultArrow', () => {
|
||||
it('renders list items from data prop', () => {
|
||||
describe("ResultArrow", () => {
|
||||
it("renders list items from data prop", () => {
|
||||
const wrapper = mount(ResultArrow, {
|
||||
props: {
|
||||
data: ['Activity A', 'Activity B', 'Activity C'],
|
||||
data: ["Activity A", "Activity B", "Activity C"],
|
||||
select: null,
|
||||
},
|
||||
});
|
||||
const items = wrapper.findAll('li');
|
||||
const items = wrapper.findAll("li");
|
||||
expect(items.length).toBe(3);
|
||||
expect(items[0].text()).toContain('Activity A');
|
||||
expect(items[1].text()).toContain('Activity B');
|
||||
expect(items[2].text()).toContain('Activity C');
|
||||
expect(items[0].text()).toContain("Activity A");
|
||||
expect(items[1].text()).toContain("Activity B");
|
||||
expect(items[2].text()).toContain("Activity C");
|
||||
});
|
||||
|
||||
it('renders empty list when data is null', () => {
|
||||
it("renders empty list when data is null", () => {
|
||||
const wrapper = mount(ResultArrow, {
|
||||
props: { data: null, select: null },
|
||||
});
|
||||
const items = wrapper.findAll('li');
|
||||
const items = wrapper.findAll("li");
|
||||
expect(items.length).toBe(0);
|
||||
});
|
||||
|
||||
it('renders arrow_circle_down icon for each item', () => {
|
||||
it("renders arrow_circle_down icon for each item", () => {
|
||||
const wrapper = mount(ResultArrow, {
|
||||
props: {
|
||||
data: ['Task 1'],
|
||||
data: ["Task 1"],
|
||||
select: null,
|
||||
},
|
||||
});
|
||||
expect(wrapper.find('span.material-symbols-outlined').text()).toContain(
|
||||
'arrow_circle_down',
|
||||
expect(wrapper.find("span.material-symbols-outlined").text()).toContain(
|
||||
"arrow_circle_down",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import ResultCheck from '@/components/Discover/Conformance/ConformanceSidebar/ResultCheck.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ResultCheck from "@/components/Discover/Conformance/ConformanceSidebar/ResultCheck.vue";
|
||||
|
||||
// Mock $emitter to prevent errors
|
||||
const mockEmitter = { on: () => {}, emit: () => {} };
|
||||
|
||||
describe('ResultCheck', () => {
|
||||
describe("ResultCheck", () => {
|
||||
const mountResultCheck = (props = {}) => {
|
||||
return mount(ResultCheck, {
|
||||
props: {
|
||||
@@ -26,41 +26,41 @@ describe('ResultCheck', () => {
|
||||
});
|
||||
};
|
||||
|
||||
it('renders list from select prop on creation', () => {
|
||||
it("renders list from select prop on creation", () => {
|
||||
const wrapper = mountResultCheck({
|
||||
select: ['Activity X', 'Activity Y'],
|
||||
select: ["Activity X", "Activity Y"],
|
||||
});
|
||||
const items = wrapper.findAll('li');
|
||||
const items = wrapper.findAll("li");
|
||||
expect(items.length).toBe(2);
|
||||
expect(items[0].text()).toContain('Activity X');
|
||||
expect(items[1].text()).toContain('Activity Y');
|
||||
expect(items[0].text()).toContain("Activity X");
|
||||
expect(items[1].text()).toContain("Activity Y");
|
||||
});
|
||||
|
||||
it('renders empty when select is null', () => {
|
||||
it("renders empty when select is null", () => {
|
||||
const wrapper = mountResultCheck({ select: null });
|
||||
const items = wrapper.findAll('li');
|
||||
const items = wrapper.findAll("li");
|
||||
expect(items.length).toBe(0);
|
||||
});
|
||||
|
||||
it('renders check_circle icon for each item', () => {
|
||||
const wrapper = mountResultCheck({ select: ['Task 1'] });
|
||||
expect(wrapper.find('span.material-symbols-outlined').text()).toContain(
|
||||
'check_circle',
|
||||
it("renders check_circle icon for each item", () => {
|
||||
const wrapper = mountResultCheck({ select: ["Task 1"] });
|
||||
expect(wrapper.find("span.material-symbols-outlined").text()).toContain(
|
||||
"check_circle",
|
||||
);
|
||||
});
|
||||
|
||||
it('updates list when data prop changes', async () => {
|
||||
const wrapper = mountResultCheck({ select: ['Initial'] });
|
||||
expect(wrapper.findAll('li').length).toBe(1);
|
||||
it("updates list when data prop changes", async () => {
|
||||
const wrapper = mountResultCheck({ select: ["Initial"] });
|
||||
expect(wrapper.findAll("li").length).toBe(1);
|
||||
|
||||
await wrapper.setProps({ data: ['New A', 'New B'] });
|
||||
expect(wrapper.findAll('li').length).toBe(2);
|
||||
expect(wrapper.text()).toContain('New A');
|
||||
await wrapper.setProps({ data: ["New A", "New B"] });
|
||||
expect(wrapper.findAll("li").length).toBe(2);
|
||||
expect(wrapper.text()).toContain("New A");
|
||||
});
|
||||
|
||||
it('updates list when select prop changes', async () => {
|
||||
const wrapper = mountResultCheck({ select: ['Old'] });
|
||||
await wrapper.setProps({ select: ['Changed'] });
|
||||
expect(wrapper.text()).toContain('Changed');
|
||||
it("updates list when select prop changes", async () => {
|
||||
const wrapper = mountResultCheck({ select: ["Old"] });
|
||||
await wrapper.setProps({ select: ["Changed"] });
|
||||
expect(wrapper.text()).toContain("Changed");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import ResultDot from '@/components/Discover/Conformance/ConformanceSidebar/ResultDot.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import ResultDot from "@/components/Discover/Conformance/ConformanceSidebar/ResultDot.vue";
|
||||
|
||||
// Mock $emitter to prevent errors
|
||||
const mockEmitter = { on: () => {}, emit: () => {} };
|
||||
|
||||
describe('ResultDot', () => {
|
||||
describe("ResultDot", () => {
|
||||
const mountResultDot = (props = {}) => {
|
||||
return mount(ResultDot, {
|
||||
props: {
|
||||
@@ -26,31 +26,31 @@ describe('ResultDot', () => {
|
||||
});
|
||||
};
|
||||
|
||||
it('renders list from select prop on creation', () => {
|
||||
it("renders list from select prop on creation", () => {
|
||||
const data = [
|
||||
{ category: 'Start', task: 'Task A' },
|
||||
{ category: 'End', task: 'Task B' },
|
||||
{ category: "Start", task: "Task A" },
|
||||
{ category: "End", task: "Task B" },
|
||||
];
|
||||
const wrapper = mountResultDot({ select: data });
|
||||
const items = wrapper.findAll('li');
|
||||
const items = wrapper.findAll("li");
|
||||
expect(items.length).toBe(2);
|
||||
expect(items[0].text()).toContain('Start');
|
||||
expect(items[0].text()).toContain('Task A');
|
||||
expect(items[0].text()).toContain("Start");
|
||||
expect(items[0].text()).toContain("Task A");
|
||||
});
|
||||
|
||||
it('renders empty when select is null', () => {
|
||||
it("renders empty when select is null", () => {
|
||||
const wrapper = mountResultDot({ select: null });
|
||||
const items = wrapper.findAll('li');
|
||||
const items = wrapper.findAll("li");
|
||||
expect(items.length).toBe(0);
|
||||
});
|
||||
|
||||
it('updates list when timeResultData prop changes', async () => {
|
||||
it("updates list when timeResultData prop changes", async () => {
|
||||
const wrapper = mountResultDot({ select: null });
|
||||
expect(wrapper.findAll('li').length).toBe(0);
|
||||
expect(wrapper.findAll("li").length).toBe(0);
|
||||
|
||||
const newData = [{ category: 'Mid', task: 'Task C' }];
|
||||
const newData = [{ category: "Mid", task: "Task C" }];
|
||||
await wrapper.setProps({ timeResultData: newData });
|
||||
expect(wrapper.findAll('li').length).toBe(1);
|
||||
expect(wrapper.text()).toContain('Task C');
|
||||
expect(wrapper.findAll("li").length).toBe(1);
|
||||
expect(wrapper.text()).toContain("Task C");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mount } from '@vue/test-utils';
|
||||
import Search from '@/components/Search.vue';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mount } from "@vue/test-utils";
|
||||
import Search from "@/components/Search.vue";
|
||||
|
||||
describe('Search', () => {
|
||||
it('renders search form', () => {
|
||||
describe("Search", () => {
|
||||
it("renders search form", () => {
|
||||
const wrapper = mount(Search);
|
||||
expect(wrapper.find('form[role="search"]').exists()).toBe(true);
|
||||
});
|
||||
|
||||
it('contains search input', () => {
|
||||
it("contains search input", () => {
|
||||
const wrapper = mount(Search);
|
||||
const input = wrapper.find('input[type="search"]');
|
||||
expect(input.exists()).toBe(true);
|
||||
expect(input.attributes('placeholder')).toBe('Search Activity');
|
||||
expect(input.attributes("placeholder")).toBe("Search Activity");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/06
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
|
||||
describe('router beforeEach guard logic', () => {
|
||||
describe("router beforeEach guard logic", () => {
|
||||
beforeEach(() => {
|
||||
// Clear cookies
|
||||
document.cookie.split(';').forEach((c) => {
|
||||
const name = c.split('=')[0].trim();
|
||||
document.cookie.split(";").forEach((c) => {
|
||||
const name = c.split("=")[0].trim();
|
||||
if (name) {
|
||||
document.cookie = name + '=; Max-Age=-99999999; path=/';
|
||||
document.cookie = name + "=; Max-Age=-99999999; path=/";
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -19,26 +19,26 @@ describe('router beforeEach guard logic', () => {
|
||||
// Simulate the guard logic from router/index.ts
|
||||
function runGuard(to) {
|
||||
const isLoggedIn = document.cookie
|
||||
.split(';')
|
||||
.some((c) => c.trim().startsWith('isLuciaLoggedIn='));
|
||||
.split(";")
|
||||
.some((c) => c.trim().startsWith("isLuciaLoggedIn="));
|
||||
|
||||
if (to.name === 'Login') {
|
||||
if (isLoggedIn) return { name: 'Files' };
|
||||
if (to.name === "Login") {
|
||||
if (isLoggedIn) return { name: "Files" };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
it('redirects logged-in user from Login to Files', () => {
|
||||
document.cookie = 'isLuciaLoggedIn=true';
|
||||
expect(runGuard({ name: 'Login' })).toEqual({ name: 'Files' });
|
||||
it("redirects logged-in user from Login to Files", () => {
|
||||
document.cookie = "isLuciaLoggedIn=true";
|
||||
expect(runGuard({ name: "Login" })).toEqual({ name: "Files" });
|
||||
});
|
||||
|
||||
it('allows unauthenticated user to visit Login', () => {
|
||||
expect(runGuard({ name: 'Login' })).toBeUndefined();
|
||||
it("allows unauthenticated user to visit Login", () => {
|
||||
expect(runGuard({ name: "Login" })).toBeUndefined();
|
||||
});
|
||||
|
||||
it('does not interfere with non-Login routes', () => {
|
||||
document.cookie = 'isLuciaLoggedIn=true';
|
||||
expect(runGuard({ name: 'Files' })).toBeUndefined();
|
||||
it("does not interfere with non-Login routes", () => {
|
||||
document.cookie = "isLuciaLoggedIn=true";
|
||||
expect(runGuard({ name: "Files" })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,27 +3,30 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockGet, mockPost, mockPut, mockDelete } = vi.hoisted(() => ({
|
||||
mockGet: vi.fn(), mockPost: vi.fn(), mockPut: vi.fn(), mockDelete: vi.fn(),
|
||||
mockGet: vi.fn(),
|
||||
mockPost: vi.fn(),
|
||||
mockPut: vi.fn(),
|
||||
mockDelete: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockGet, post: mockPost, put: mockPut, delete: mockDelete },
|
||||
}));
|
||||
|
||||
// Mock login store to avoid its side effects
|
||||
vi.mock('@/stores/login', () => {
|
||||
const { defineStore } = require('pinia');
|
||||
vi.mock("@/stores/login", () => {
|
||||
const { defineStore } = require("pinia");
|
||||
return {
|
||||
useLoginStore: defineStore('loginStore', {
|
||||
useLoginStore: defineStore("loginStore", {
|
||||
state: () => ({
|
||||
userData: { username: 'currentUser', name: 'Current' },
|
||||
userData: { username: "currentUser", name: "Current" },
|
||||
}),
|
||||
actions: {
|
||||
getUserData: vi.fn(),
|
||||
@@ -32,9 +35,9 @@ vi.mock('@/stores/login', () => {
|
||||
};
|
||||
});
|
||||
|
||||
import { useAcctMgmtStore } from '@/stores/acctMgmt';
|
||||
import { useAcctMgmtStore } from "@/stores/acctMgmt";
|
||||
|
||||
describe('acctMgmtStore', () => {
|
||||
describe("acctMgmtStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -43,24 +46,24 @@ describe('acctMgmtStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.allUserAccountList).toEqual([]);
|
||||
expect(store.isAcctMenuOpen).toBe(false);
|
||||
});
|
||||
|
||||
describe('menu actions', () => {
|
||||
it('openAcctMenu sets true', () => {
|
||||
describe("menu actions", () => {
|
||||
it("openAcctMenu sets true", () => {
|
||||
store.openAcctMenu();
|
||||
expect(store.isAcctMenuOpen).toBe(true);
|
||||
});
|
||||
|
||||
it('closeAcctMenu sets false', () => {
|
||||
it("closeAcctMenu sets false", () => {
|
||||
store.openAcctMenu();
|
||||
store.closeAcctMenu();
|
||||
expect(store.isAcctMenuOpen).toBe(false);
|
||||
});
|
||||
|
||||
it('toggleIsAcctMenuOpen toggles', () => {
|
||||
it("toggleIsAcctMenuOpen toggles", () => {
|
||||
store.toggleIsAcctMenuOpen();
|
||||
expect(store.isAcctMenuOpen).toBe(true);
|
||||
store.toggleIsAcctMenuOpen();
|
||||
@@ -68,157 +71,149 @@ describe('acctMgmtStore', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('setCurrentViewingUser', () => {
|
||||
it('finds user by username', () => {
|
||||
describe("setCurrentViewingUser", () => {
|
||||
it("finds user by username", () => {
|
||||
store.allUserAccountList = [
|
||||
{ username: 'alice', name: 'Alice', detail: {} },
|
||||
{ username: 'bob', name: 'Bob', detail: {} },
|
||||
{ username: "alice", name: "Alice", detail: {} },
|
||||
{ username: "bob", name: "Bob", detail: {} },
|
||||
];
|
||||
store.setCurrentViewingUser('bob');
|
||||
expect(store.currentViewingUser.name).toBe('Bob');
|
||||
store.setCurrentViewingUser("bob");
|
||||
expect(store.currentViewingUser.name).toBe("Bob");
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearCurrentViewingUser', () => {
|
||||
it('resets to empty user', () => {
|
||||
store.currentViewingUser = { username: 'test', detail: {} };
|
||||
describe("clearCurrentViewingUser", () => {
|
||||
it("resets to empty user", () => {
|
||||
store.currentViewingUser = { username: "test", detail: {} };
|
||||
store.clearCurrentViewingUser();
|
||||
expect(store.currentViewingUser.username).toBe('');
|
||||
expect(store.currentViewingUser.username).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe('createNewAccount', () => {
|
||||
it('posts to /api/users and sets flag on success', async () => {
|
||||
describe("createNewAccount", () => {
|
||||
it("posts to /api/users and sets flag on success", async () => {
|
||||
mockPost.mockResolvedValue({ status: 200 });
|
||||
const user = { username: 'newuser', password: 'pass' };
|
||||
const user = { username: "newuser", password: "pass" };
|
||||
|
||||
await store.createNewAccount(user);
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/users', user,
|
||||
);
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/users", user);
|
||||
expect(store.isOneAccountJustCreate).toBe(true);
|
||||
expect(store.justCreateUsername).toBe('newuser');
|
||||
expect(store.justCreateUsername).toBe("newuser");
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteAccount', () => {
|
||||
it('returns true on success', async () => {
|
||||
describe("deleteAccount", () => {
|
||||
it("returns true on success", async () => {
|
||||
mockDelete.mockResolvedValue({ status: 200 });
|
||||
|
||||
const result = await store.deleteAccount('alice');
|
||||
const result = await store.deleteAccount("alice");
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith(
|
||||
'/api/users/alice',
|
||||
);
|
||||
expect(mockDelete).toHaveBeenCalledWith("/api/users/alice");
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('encodes special characters in username', async () => {
|
||||
it("encodes special characters in username", async () => {
|
||||
mockDelete.mockResolvedValue({ status: 200 });
|
||||
|
||||
await store.deleteAccount('user@domain/name');
|
||||
await store.deleteAccount("user@domain/name");
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith(
|
||||
'/api/users/user%40domain%2Fname',
|
||||
"/api/users/user%40domain%2Fname",
|
||||
);
|
||||
});
|
||||
|
||||
it('returns false on error', async () => {
|
||||
mockDelete.mockRejectedValue(new Error('fail'));
|
||||
it("returns false on error", async () => {
|
||||
mockDelete.mockRejectedValue(new Error("fail"));
|
||||
|
||||
const result = await store.deleteAccount('alice');
|
||||
const result = await store.deleteAccount("alice");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('editAccount', () => {
|
||||
it('puts edited data', async () => {
|
||||
describe("editAccount", () => {
|
||||
it("puts edited data", async () => {
|
||||
mockPut.mockResolvedValue({ status: 200 });
|
||||
const detail = {
|
||||
username: 'alice',
|
||||
password: 'newpw',
|
||||
name: 'Alice',
|
||||
username: "alice",
|
||||
password: "newpw",
|
||||
name: "Alice",
|
||||
is_active: true,
|
||||
};
|
||||
|
||||
const result = await store.editAccount('alice', detail);
|
||||
const result = await store.editAccount("alice", detail);
|
||||
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
'/api/users/alice',
|
||||
expect.objectContaining({ password: 'newpw' }),
|
||||
"/api/users/alice",
|
||||
expect.objectContaining({ password: "newpw" }),
|
||||
);
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addRoleToUser', () => {
|
||||
it('puts role assignment', async () => {
|
||||
describe("addRoleToUser", () => {
|
||||
it("puts role assignment", async () => {
|
||||
mockPut.mockResolvedValue({ status: 200 });
|
||||
|
||||
const result = await store.addRoleToUser('alice', 'admin');
|
||||
const result = await store.addRoleToUser("alice", "admin");
|
||||
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
'/api/users/alice/roles/admin',
|
||||
);
|
||||
expect(mockPut).toHaveBeenCalledWith("/api/users/alice/roles/admin");
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
|
||||
it('encodes special characters in username and role', async () => {
|
||||
it("encodes special characters in username and role", async () => {
|
||||
mockPut.mockResolvedValue({ status: 200 });
|
||||
|
||||
await store.addRoleToUser('user@org', 'role/special');
|
||||
await store.addRoleToUser("user@org", "role/special");
|
||||
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
'/api/users/user%40org/roles/role%2Fspecial',
|
||||
"/api/users/user%40org/roles/role%2Fspecial",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteRoleToUser', () => {
|
||||
it('deletes role', async () => {
|
||||
describe("deleteRoleToUser", () => {
|
||||
it("deletes role", async () => {
|
||||
mockDelete.mockResolvedValue({ status: 200 });
|
||||
|
||||
const result = await store.deleteRoleToUser('alice', 'admin');
|
||||
const result = await store.deleteRoleToUser("alice", "admin");
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith(
|
||||
'/api/users/alice/roles/admin',
|
||||
);
|
||||
expect(mockDelete).toHaveBeenCalledWith("/api/users/alice/roles/admin");
|
||||
expect(result).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getUserDetail', () => {
|
||||
it('fetches user and sets admin flag', async () => {
|
||||
describe("getUserDetail", () => {
|
||||
it("fetches user and sets admin flag", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
status: 200,
|
||||
data: {
|
||||
username: 'alice',
|
||||
roles: [{ code: 'admin' }],
|
||||
username: "alice",
|
||||
roles: [{ code: "admin" }],
|
||||
},
|
||||
});
|
||||
|
||||
const result = await store.getUserDetail('alice');
|
||||
const result = await store.getUserDetail("alice");
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(store.currentViewingUser.is_admin).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false on error', async () => {
|
||||
mockGet.mockRejectedValue(new Error('not found'));
|
||||
it("returns false on error", async () => {
|
||||
mockGet.mockRejectedValue(new Error("not found"));
|
||||
|
||||
const result = await store.getUserDetail('ghost');
|
||||
const result = await store.getUserDetail("ghost");
|
||||
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hover state actions', () => {
|
||||
describe("hover state actions", () => {
|
||||
beforeEach(() => {
|
||||
store.allUserAccountList = [
|
||||
{
|
||||
username: 'alice',
|
||||
username: "alice",
|
||||
isDeleteHovered: false,
|
||||
isRowHovered: false,
|
||||
isEditHovered: false,
|
||||
@@ -227,45 +222,44 @@ describe('acctMgmtStore', () => {
|
||||
];
|
||||
});
|
||||
|
||||
it('changeIsDeleteHoveredByUser', () => {
|
||||
store.changeIsDeleteHoveredByUser('alice', true);
|
||||
it("changeIsDeleteHoveredByUser", () => {
|
||||
store.changeIsDeleteHoveredByUser("alice", true);
|
||||
expect(store.allUserAccountList[0].isDeleteHovered).toBe(true);
|
||||
});
|
||||
|
||||
it('changeIsRowHoveredByUser', () => {
|
||||
store.changeIsRowHoveredByUser('alice', true);
|
||||
it("changeIsRowHoveredByUser", () => {
|
||||
store.changeIsRowHoveredByUser("alice", true);
|
||||
expect(store.allUserAccountList[0].isRowHovered).toBe(true);
|
||||
});
|
||||
|
||||
it('changeIsEditHoveredByUser', () => {
|
||||
store.changeIsEditHoveredByUser('alice', true);
|
||||
it("changeIsEditHoveredByUser", () => {
|
||||
store.changeIsEditHoveredByUser("alice", true);
|
||||
expect(store.allUserAccountList[0].isEditHovered).toBe(true);
|
||||
});
|
||||
|
||||
it('changeIsDetailHoveredByUser', () => {
|
||||
store.changeIsDetailHoveredByUser('alice', true);
|
||||
it("changeIsDetailHoveredByUser", () => {
|
||||
store.changeIsDetailHoveredByUser("alice", true);
|
||||
expect(store.allUserAccountList[0].isDetailHovered).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('resetJustCreateFlag resets flag', () => {
|
||||
it("resetJustCreateFlag resets flag", () => {
|
||||
store.isOneAccountJustCreate = true;
|
||||
store.resetJustCreateFlag();
|
||||
expect(store.isOneAccountJustCreate).toBe(false);
|
||||
});
|
||||
|
||||
it('setShouldUpdateList sets boolean', () => {
|
||||
it("setShouldUpdateList sets boolean", () => {
|
||||
store.setShouldUpdateList(true);
|
||||
expect(store.shouldUpdateList).toBe(true);
|
||||
});
|
||||
|
||||
it('updateSingleAccountPiniaState updates user', () => {
|
||||
store.allUserAccountList = [
|
||||
{ username: 'alice', name: 'Old' },
|
||||
];
|
||||
it("updateSingleAccountPiniaState updates user", () => {
|
||||
store.allUserAccountList = [{ username: "alice", name: "Old" }];
|
||||
store.updateSingleAccountPiniaState({
|
||||
username: 'alice', name: 'New',
|
||||
username: "alice",
|
||||
name: "New",
|
||||
});
|
||||
expect(store.allUserAccountList[0].name).toBe('New');
|
||||
expect(store.allUserAccountList[0].name).toBe("New");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,23 +3,25 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockGet, mockPost, mockPut } = vi.hoisted(() => ({
|
||||
mockGet: vi.fn(), mockPost: vi.fn(), mockPut: vi.fn(),
|
||||
mockGet: vi.fn(),
|
||||
mockPost: vi.fn(),
|
||||
mockPut: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockGet, post: mockPost, put: mockPut },
|
||||
}));
|
||||
|
||||
import { useAllMapDataStore } from '@/stores/allMapData';
|
||||
import { useAllMapDataStore } from "@/stores/allMapData";
|
||||
|
||||
describe('allMapDataStore', () => {
|
||||
describe("allMapDataStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -28,14 +30,14 @@ describe('allMapDataStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.logId).toBeNull();
|
||||
expect(store.allProcessMap).toEqual({});
|
||||
expect(store.allTrace).toEqual([]);
|
||||
});
|
||||
|
||||
describe('getAllMapData', () => {
|
||||
it('fetches log discover data', async () => {
|
||||
describe("getAllMapData", () => {
|
||||
it("fetches log discover data", async () => {
|
||||
store.logId = 1;
|
||||
const mockData = {
|
||||
process_map: { nodes: [] },
|
||||
@@ -47,14 +49,12 @@ describe('allMapDataStore', () => {
|
||||
|
||||
await store.getAllMapData();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/logs/1/discover',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/logs/1/discover");
|
||||
expect(store.allProcessMap).toEqual({ nodes: [] });
|
||||
expect(store.allStats).toEqual({ cases: 10 });
|
||||
});
|
||||
|
||||
it('fetches temp filter discover data when set', async () => {
|
||||
it("fetches temp filter discover data when set", async () => {
|
||||
store.logId = 1;
|
||||
store.tempFilterId = 5;
|
||||
mockGet.mockResolvedValue({
|
||||
@@ -68,12 +68,10 @@ describe('allMapDataStore', () => {
|
||||
|
||||
await store.getAllMapData();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/temp-filters/5/discover',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/temp-filters/5/discover");
|
||||
});
|
||||
|
||||
it('fetches created filter discover data', async () => {
|
||||
it("fetches created filter discover data", async () => {
|
||||
store.logId = 1;
|
||||
store.createFilterId = 3;
|
||||
mockGet.mockResolvedValue({
|
||||
@@ -87,31 +85,28 @@ describe('allMapDataStore', () => {
|
||||
|
||||
await store.getAllMapData();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/filters/3/discover',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/filters/3/discover");
|
||||
});
|
||||
|
||||
it('does not throw on API failure', async () => {
|
||||
it("does not throw on API failure", async () => {
|
||||
store.logId = 1;
|
||||
mockGet.mockRejectedValue(new Error('fail'));
|
||||
mockGet.mockRejectedValue(new Error("fail"));
|
||||
|
||||
await expect(store.getAllMapData())
|
||||
.resolves.not.toThrow();
|
||||
await expect(store.getAllMapData()).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFilterParams', () => {
|
||||
it('fetches filter params and transforms timeframe', async () => {
|
||||
describe("getFilterParams", () => {
|
||||
it("fetches filter params and transforms timeframe", async () => {
|
||||
store.logId = 1;
|
||||
const mockData = {
|
||||
tasks: ['A', 'B'],
|
||||
sources: ['A'],
|
||||
sinks: ['B'],
|
||||
tasks: ["A", "B"],
|
||||
sources: ["A"],
|
||||
sinks: ["B"],
|
||||
timeframe: {
|
||||
x_axis: {
|
||||
min: '2023-01-01T00:00:00Z',
|
||||
max: '2023-12-31T00:00:00Z',
|
||||
min: "2023-01-01T00:00:00Z",
|
||||
max: "2023-12-31T00:00:00Z",
|
||||
},
|
||||
},
|
||||
trace: [],
|
||||
@@ -121,20 +116,19 @@ describe('allMapDataStore', () => {
|
||||
|
||||
await store.getFilterParams();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/filters/params?log_id=1',
|
||||
);
|
||||
expect(store.allFilterTask).toEqual(['A', 'B']);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/filters/params?log_id=1");
|
||||
expect(store.allFilterTask).toEqual(["A", "B"]);
|
||||
// Check that min_base and max_base are stored
|
||||
expect(store.allFilterTimeframe.x_axis.min_base)
|
||||
.toBe('2023-01-01T00:00:00Z');
|
||||
expect(store.allFilterTimeframe.x_axis.min_base).toBe(
|
||||
"2023-01-01T00:00:00Z",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkHasResult', () => {
|
||||
it('posts rule data and stores result', async () => {
|
||||
describe("checkHasResult", () => {
|
||||
it("posts rule data and stores result", async () => {
|
||||
store.logId = 1;
|
||||
store.postRuleData = [{ type: 'task' }];
|
||||
store.postRuleData = [{ type: "task" }];
|
||||
mockPost.mockResolvedValue({
|
||||
data: { result: true },
|
||||
});
|
||||
@@ -142,15 +136,15 @@ describe('allMapDataStore', () => {
|
||||
await store.checkHasResult();
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/filters/has-result?log_id=1',
|
||||
[{ type: 'task' }],
|
||||
"/api/filters/has-result?log_id=1",
|
||||
[{ type: "task" }],
|
||||
);
|
||||
expect(store.hasResultRule).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addTempFilterId', () => {
|
||||
it('creates temp filter and stores id', async () => {
|
||||
describe("addTempFilterId", () => {
|
||||
it("creates temp filter and stores id", async () => {
|
||||
store.logId = 1;
|
||||
store.postRuleData = [];
|
||||
mockPost.mockResolvedValue({ data: { id: 77 } });
|
||||
@@ -161,44 +155,43 @@ describe('allMapDataStore', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('addFilterId', () => {
|
||||
it('creates filter and clears temp id', async () => {
|
||||
describe("addFilterId", () => {
|
||||
it("creates filter and clears temp id", async () => {
|
||||
store.logId = 1;
|
||||
store.tempFilterId = 77;
|
||||
store.postRuleData = [{ type: 'rule' }];
|
||||
store.postRuleData = [{ type: "rule" }];
|
||||
mockPost.mockResolvedValue({ data: { id: 88 } });
|
||||
|
||||
await store.addFilterId('myFilter');
|
||||
await store.addFilterId("myFilter");
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/filters?log_id=1',
|
||||
{ name: 'myFilter', rules: [{ type: 'rule' }] },
|
||||
);
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/filters?log_id=1", {
|
||||
name: "myFilter",
|
||||
rules: [{ type: "rule" }],
|
||||
});
|
||||
expect(store.createFilterId).toBe(88);
|
||||
expect(store.tempFilterId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateFilter', () => {
|
||||
it('updates filter and clears temp id', async () => {
|
||||
describe("updateFilter", () => {
|
||||
it("updates filter and clears temp id", async () => {
|
||||
store.createFilterId = 88;
|
||||
store.tempFilterId = 77;
|
||||
store.postRuleData = [{ type: 'updated' }];
|
||||
store.postRuleData = [{ type: "updated" }];
|
||||
mockPut.mockResolvedValue({ status: 200 });
|
||||
|
||||
await store.updateFilter();
|
||||
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
'/api/filters/88',
|
||||
[{ type: 'updated' }],
|
||||
);
|
||||
expect(mockPut).toHaveBeenCalledWith("/api/filters/88", [
|
||||
{ type: "updated" },
|
||||
]);
|
||||
expect(store.isUpdateFilter).toBe(true);
|
||||
expect(store.tempFilterId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAllTrace', () => {
|
||||
it('does not crash when baseLogId is falsy', async () => {
|
||||
describe("getAllTrace", () => {
|
||||
it("does not crash when baseLogId is falsy", async () => {
|
||||
store.logId = 1;
|
||||
store.baseLogId = null;
|
||||
mockGet.mockResolvedValue({ data: [{ id: 1 }] });
|
||||
@@ -211,37 +204,37 @@ describe('allMapDataStore', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('getters', () => {
|
||||
it('traces getter sorts by id', () => {
|
||||
describe("getters", () => {
|
||||
it("traces getter sorts by id", () => {
|
||||
store.allTrace = [
|
||||
{ id: 3, name: 'C' },
|
||||
{ id: 1, name: 'A' },
|
||||
{ id: 2, name: 'B' },
|
||||
{ id: 3, name: "C" },
|
||||
{ id: 1, name: "A" },
|
||||
{ id: 2, name: "B" },
|
||||
];
|
||||
expect(store.traces.map(t => t.id)).toEqual([1, 2, 3]);
|
||||
expect(store.traces.map((t) => t.id)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('processMap getter returns state', () => {
|
||||
it("processMap getter returns state", () => {
|
||||
store.allProcessMap = { nodes: [1, 2] };
|
||||
expect(store.processMap).toEqual({ nodes: [1, 2] });
|
||||
});
|
||||
|
||||
it('BaseInfiniteFirstCases returns allBaseCase when baseInfiniteStart is 0', () => {
|
||||
it("BaseInfiniteFirstCases returns allBaseCase when baseInfiniteStart is 0", () => {
|
||||
store.baseInfiniteStart = 0;
|
||||
store.allBaseCase = [{ id: 1 }, { id: 2 }];
|
||||
expect(store.BaseInfiniteFirstCases).toEqual([{ id: 1 }, { id: 2 }]);
|
||||
});
|
||||
|
||||
it('BaseInfiniteFirstCases returns undefined when baseInfiniteStart is not 0', () => {
|
||||
it("BaseInfiniteFirstCases returns undefined when baseInfiniteStart is not 0", () => {
|
||||
store.baseInfiniteStart = 5;
|
||||
store.allBaseCase = [{ id: 1 }];
|
||||
expect(store.BaseInfiniteFirstCases).toBeUndefined();
|
||||
});
|
||||
|
||||
it('filterAttrs getter does not corrupt original state on repeated access', () => {
|
||||
const originalDate = '2023-06-15T10:30:00Z';
|
||||
it("filterAttrs getter does not corrupt original state on repeated access", () => {
|
||||
const originalDate = "2023-06-15T10:30:00Z";
|
||||
store.allFilterAttrs = [
|
||||
{ type: 'date', min: originalDate, max: '2023-12-31T23:59:00Z' },
|
||||
{ type: "date", min: originalDate, max: "2023-12-31T23:59:00Z" },
|
||||
];
|
||||
// Access the getter once
|
||||
store.filterAttrs;
|
||||
@@ -249,10 +242,8 @@ describe('allMapDataStore', () => {
|
||||
expect(store.allFilterAttrs[0].min).toBe(originalDate);
|
||||
});
|
||||
|
||||
it('filterAttrs getter returns consistent float values on repeated access', () => {
|
||||
store.allFilterAttrs = [
|
||||
{ type: 'float', min: 1.239, max: 5.671 },
|
||||
];
|
||||
it("filterAttrs getter returns consistent float values on repeated access", () => {
|
||||
store.allFilterAttrs = [{ type: "float", min: 1.239, max: 5.671 }];
|
||||
const first = store.filterAttrs;
|
||||
const second = store.filterAttrs;
|
||||
// min rounds down (ROUND_DOWN=1), max rounds up (ROUND_UP=0)
|
||||
|
||||
@@ -3,21 +3,21 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() }));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockGet },
|
||||
}));
|
||||
|
||||
import { useCompareStore } from '@/stores/compare';
|
||||
import { useCompareStore } from "@/stores/compare";
|
||||
|
||||
describe('compareStore', () => {
|
||||
describe("compareStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -26,83 +26,76 @@ describe('compareStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.allCompareDashboardData).toBeNull();
|
||||
});
|
||||
|
||||
it('compareDashboardData getter returns state', () => {
|
||||
it("compareDashboardData getter returns state", () => {
|
||||
store.allCompareDashboardData = { time: {} };
|
||||
expect(store.compareDashboardData).toEqual({ time: {} });
|
||||
});
|
||||
|
||||
describe('getCompare', () => {
|
||||
it('fetches compare data with encoded params', async () => {
|
||||
const params = [{ type: 'log', id: 1 }];
|
||||
describe("getCompare", () => {
|
||||
it("fetches compare data with encoded params", async () => {
|
||||
const params = [{ type: "log", id: 1 }];
|
||||
const mockData = { time: {}, freq: {} };
|
||||
mockGet.mockResolvedValue({ data: mockData });
|
||||
|
||||
await store.getCompare(params);
|
||||
|
||||
const encoded = encodeURIComponent(JSON.stringify(params));
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
`/api/compare?datasets=${encoded}`,
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith(`/api/compare?datasets=${encoded}`);
|
||||
expect(store.allCompareDashboardData).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('does not throw on API failure', async () => {
|
||||
mockGet.mockRejectedValue(new Error('fail'));
|
||||
it("does not throw on API failure", async () => {
|
||||
mockGet.mockRejectedValue(new Error("fail"));
|
||||
|
||||
await expect(store.getCompare([]))
|
||||
.resolves.not.toThrow();
|
||||
await expect(store.getCompare([])).resolves.not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStateData', () => {
|
||||
it('fetches log discover stats', async () => {
|
||||
describe("getStateData", () => {
|
||||
it("fetches log discover stats", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
data: { stats: { cases: 100 } },
|
||||
});
|
||||
|
||||
const result = await store.getStateData('log', 1);
|
||||
const result = await store.getStateData("log", 1);
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/logs/1/discover',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/logs/1/discover");
|
||||
expect(result).toEqual({ cases: 100 });
|
||||
});
|
||||
|
||||
it('fetches filter discover stats', async () => {
|
||||
it("fetches filter discover stats", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
data: { stats: { cases: 50 } },
|
||||
});
|
||||
|
||||
const result = await store.getStateData('filter', 3);
|
||||
const result = await store.getStateData("filter", 3);
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/filters/3/discover',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/filters/3/discover");
|
||||
expect(result).toEqual({ cases: 50 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getFileName', () => {
|
||||
it('finds file name by id', async () => {
|
||||
describe("getFileName", () => {
|
||||
it("finds file name by id", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
data: [
|
||||
{ id: 1, name: 'file1.csv' },
|
||||
{ id: 2, name: 'file2.csv' },
|
||||
{ id: 1, name: "file1.csv" },
|
||||
{ id: 2, name: "file2.csv" },
|
||||
],
|
||||
});
|
||||
|
||||
const result = await store.getFileName(1);
|
||||
|
||||
expect(result).toBe('file1.csv');
|
||||
expect(result).toBe("file1.csv");
|
||||
});
|
||||
|
||||
it('returns undefined for non-existent id', async () => {
|
||||
it("returns undefined for non-existent id", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
data: [{ id: 1, name: 'file1.csv' }],
|
||||
data: [{ id: 1, name: "file1.csv" }],
|
||||
});
|
||||
|
||||
const result = await store.getFileName(99);
|
||||
|
||||
@@ -3,24 +3,26 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockGet, mockPost, mockPut } = vi.hoisted(() => ({
|
||||
mockGet: vi.fn(), mockPost: vi.fn(), mockPut: vi.fn(),
|
||||
mockGet: vi.fn(),
|
||||
mockPost: vi.fn(),
|
||||
mockPut: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockGet, post: mockPost, put: mockPut },
|
||||
}));
|
||||
|
||||
import apiError from '@/module/apiError.js';
|
||||
import { useConformanceStore } from '@/stores/conformance';
|
||||
import apiError from "@/module/apiError.js";
|
||||
import { useConformanceStore } from "@/stores/conformance";
|
||||
|
||||
describe('conformanceStore', () => {
|
||||
describe("conformanceStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -29,21 +31,21 @@ describe('conformanceStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.conformanceLogId).toBeNull();
|
||||
expect(store.conformanceFilterId).toBeNull();
|
||||
expect(store.allConformanceTask).toEqual([]);
|
||||
expect(store.selectedRuleType).toBe('Have activity');
|
||||
expect(store.selectedRuleType).toBe("Have activity");
|
||||
});
|
||||
|
||||
describe('getConformanceParams', () => {
|
||||
it('fetches log check params when no filter', async () => {
|
||||
describe("getConformanceParams", () => {
|
||||
it("fetches log check params when no filter", async () => {
|
||||
store.conformanceLogId = 1;
|
||||
store.conformanceFilterId = null;
|
||||
const mockData = {
|
||||
tasks: [{ label: 'A' }],
|
||||
sources: ['A'],
|
||||
sinks: ['B'],
|
||||
tasks: [{ label: "A" }],
|
||||
sources: ["A"],
|
||||
sinks: ["B"],
|
||||
processing_time: {},
|
||||
waiting_time: {},
|
||||
cycle_time: {},
|
||||
@@ -52,14 +54,12 @@ describe('conformanceStore', () => {
|
||||
|
||||
await store.getConformanceParams();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/log-checks/params?log_id=1',
|
||||
);
|
||||
expect(store.allConformanceTask).toEqual([{ label: 'A' }]);
|
||||
expect(store.allCfmSeqStart).toEqual(['A']);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/log-checks/params?log_id=1");
|
||||
expect(store.allConformanceTask).toEqual([{ label: "A" }]);
|
||||
expect(store.allCfmSeqStart).toEqual(["A"]);
|
||||
});
|
||||
|
||||
it('fetches filter check params when filter set', async () => {
|
||||
it("fetches filter check params when filter set", async () => {
|
||||
store.conformanceFilterId = 5;
|
||||
const mockData = {
|
||||
tasks: [],
|
||||
@@ -74,137 +74,137 @@ describe('conformanceStore', () => {
|
||||
await store.getConformanceParams();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/filter-checks/params?filter_id=5',
|
||||
"/api/filter-checks/params?filter_id=5",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addConformanceCheckId', () => {
|
||||
it('posts to log temp-check and stores id', async () => {
|
||||
describe("addConformanceCheckId", () => {
|
||||
it("posts to log temp-check and stores id", async () => {
|
||||
store.conformanceLogId = 1;
|
||||
store.conformanceFilterId = null;
|
||||
mockPost.mockResolvedValue({ data: { id: 42 } });
|
||||
|
||||
await store.addConformanceCheckId({ rule: 'test' });
|
||||
await store.addConformanceCheckId({ rule: "test" });
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/temp-log-checks?log_id=1',
|
||||
{ rule: 'test' },
|
||||
);
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/temp-log-checks?log_id=1", {
|
||||
rule: "test",
|
||||
});
|
||||
expect(store.conformanceLogTempCheckId).toBe(42);
|
||||
});
|
||||
|
||||
it('posts to filter temp-check when filter set', async () => {
|
||||
it("posts to filter temp-check when filter set", async () => {
|
||||
store.conformanceFilterId = 3;
|
||||
mockPost.mockResolvedValue({ data: { id: 99 } });
|
||||
|
||||
await store.addConformanceCheckId({ rule: 'test' });
|
||||
await store.addConformanceCheckId({ rule: "test" });
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/temp-filter-checks?filter_id=3',
|
||||
{ rule: 'test' },
|
||||
"/api/temp-filter-checks?filter_id=3",
|
||||
{ rule: "test" },
|
||||
);
|
||||
expect(store.conformanceFilterTempCheckId).toBe(99);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getConformanceReport', () => {
|
||||
it('fetches temp log check report', async () => {
|
||||
describe("getConformanceReport", () => {
|
||||
it("fetches temp log check report", async () => {
|
||||
store.conformanceLogTempCheckId = 10;
|
||||
const mockData = { file: {}, charts: {} };
|
||||
mockGet.mockResolvedValue({ data: mockData });
|
||||
|
||||
await store.getConformanceReport();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/temp-log-checks/10',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/temp-log-checks/10");
|
||||
expect(store.allConformanceTempReportData).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('stores routeFile when getRouteFile=true', async () => {
|
||||
it("stores routeFile when getRouteFile=true", async () => {
|
||||
store.conformanceLogTempCheckId = 10;
|
||||
const mockData = { file: { name: 'test.csv' } };
|
||||
const mockData = { file: { name: "test.csv" } };
|
||||
mockGet.mockResolvedValue({ data: mockData });
|
||||
|
||||
await store.getConformanceReport(true);
|
||||
|
||||
expect(store.allRouteFile).toEqual({ name: 'test.csv' });
|
||||
expect(store.allRouteFile).toEqual({ name: "test.csv" });
|
||||
expect(store.allConformanceTempReportData).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('addConformanceCreateCheckId', () => {
|
||||
it('creates log check and clears temp id', async () => {
|
||||
describe("addConformanceCreateCheckId", () => {
|
||||
it("creates log check and clears temp id", async () => {
|
||||
store.conformanceLogId = 1;
|
||||
store.conformanceFilterId = null;
|
||||
store.conformanceLogTempCheckId = 10;
|
||||
store.conformanceRuleData = { type: 'test' };
|
||||
store.conformanceRuleData = { type: "test" };
|
||||
mockPost.mockResolvedValue({ data: { id: 100 } });
|
||||
|
||||
await store.addConformanceCreateCheckId('myRule');
|
||||
await store.addConformanceCreateCheckId("myRule");
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/log-checks?log_id=1',
|
||||
{ name: 'myRule', rule: { type: 'test' } },
|
||||
);
|
||||
expect(mockPost).toHaveBeenCalledWith("/api/log-checks?log_id=1", {
|
||||
name: "myRule",
|
||||
rule: { type: "test" },
|
||||
});
|
||||
expect(store.conformanceLogCreateCheckId).toBe(100);
|
||||
expect(store.conformanceLogTempCheckId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateConformance', () => {
|
||||
it('updates existing log check', async () => {
|
||||
describe("updateConformance", () => {
|
||||
it("updates existing log check", async () => {
|
||||
store.conformanceLogCreateCheckId = 50;
|
||||
store.conformanceRuleData = { type: 'updated' };
|
||||
store.conformanceRuleData = { type: "updated" };
|
||||
mockPut.mockResolvedValue({ status: 200 });
|
||||
|
||||
await store.updateConformance();
|
||||
|
||||
expect(mockPut).toHaveBeenCalledWith(
|
||||
'/api/log-checks/50',
|
||||
{ type: 'updated' },
|
||||
);
|
||||
expect(mockPut).toHaveBeenCalledWith("/api/log-checks/50", {
|
||||
type: "updated",
|
||||
});
|
||||
expect(store.isUpdateConformance).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('setConformanceLogCreateCheckId sets value', () => {
|
||||
store.setConformanceLogCreateCheckId('abc');
|
||||
expect(store.conformanceLogCreateCheckId).toBe('abc');
|
||||
it("setConformanceLogCreateCheckId sets value", () => {
|
||||
store.setConformanceLogCreateCheckId("abc");
|
||||
expect(store.conformanceLogCreateCheckId).toBe("abc");
|
||||
});
|
||||
|
||||
describe('getters', () => {
|
||||
it('conformanceTask returns labels', () => {
|
||||
store.allConformanceTask = [
|
||||
{ label: 'A' }, { label: 'B' },
|
||||
];
|
||||
expect(store.conformanceTask).toEqual(['A', 'B']);
|
||||
describe("getters", () => {
|
||||
it("conformanceTask returns labels", () => {
|
||||
store.allConformanceTask = [{ label: "A" }, { label: "B" }];
|
||||
expect(store.conformanceTask).toEqual(["A", "B"]);
|
||||
});
|
||||
|
||||
it('cases getter formats date attributes with correct minute token', () => {
|
||||
store.allCases = [{
|
||||
started_at: '2023-06-15T10:30:00Z',
|
||||
completed_at: '2023-06-15T11:45:00Z',
|
||||
facets: [],
|
||||
attributes: [{
|
||||
type: 'date',
|
||||
value: '2023-06-15T14:30:00Z',
|
||||
}],
|
||||
}];
|
||||
it("cases getter formats date attributes with correct minute token", () => {
|
||||
store.allCases = [
|
||||
{
|
||||
started_at: "2023-06-15T10:30:00Z",
|
||||
completed_at: "2023-06-15T11:45:00Z",
|
||||
facets: [],
|
||||
attributes: [
|
||||
{
|
||||
type: "date",
|
||||
value: "2023-06-15T14:30:00Z",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
const result = store.cases;
|
||||
// The date attribute should show minutes (30), not month (06)
|
||||
expect(result[0].attributes[0].value).toMatch(/:30:/);
|
||||
});
|
||||
|
||||
it('cases getter does not corrupt original state on repeated access', () => {
|
||||
const originalDate = '2023-06-15T10:30:00Z';
|
||||
store.allCases = [{
|
||||
started_at: originalDate,
|
||||
completed_at: '2023-06-15T11:45:00Z',
|
||||
facets: [],
|
||||
attributes: [],
|
||||
}];
|
||||
it("cases getter does not corrupt original state on repeated access", () => {
|
||||
const originalDate = "2023-06-15T10:30:00Z";
|
||||
store.allCases = [
|
||||
{
|
||||
started_at: originalDate,
|
||||
completed_at: "2023-06-15T11:45:00Z",
|
||||
facets: [],
|
||||
attributes: [],
|
||||
},
|
||||
];
|
||||
store.cases;
|
||||
// Original state should still contain the ISO date
|
||||
expect(store.allCases[0].started_at).toBe(originalDate);
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { useConformanceInputStore } from '@/stores/conformanceInput';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { useConformanceInputStore } from "@/stores/conformanceInput";
|
||||
|
||||
describe('conformanceInputStore', () => {
|
||||
describe("conformanceInputStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -15,23 +15,23 @@ describe('conformanceInputStore', () => {
|
||||
store = useConformanceInputStore();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.inputDataToSave.inputStart).toBeNull();
|
||||
expect(store.activityRadioData.task).toEqual(['', '']);
|
||||
expect(store.activityRadioData.task).toEqual(["", ""]);
|
||||
});
|
||||
|
||||
it('setActivityRadioStartEndData sets From', () => {
|
||||
store.setActivityRadioStartEndData('taskA', 'From');
|
||||
expect(store.activityRadioData.task[0]).toBe('taskA');
|
||||
it("setActivityRadioStartEndData sets From", () => {
|
||||
store.setActivityRadioStartEndData("taskA", "From");
|
||||
expect(store.activityRadioData.task[0]).toBe("taskA");
|
||||
});
|
||||
|
||||
it('setActivityRadioStartEndData sets To', () => {
|
||||
store.setActivityRadioStartEndData('taskB', 'To');
|
||||
expect(store.activityRadioData.task[1]).toBe('taskB');
|
||||
it("setActivityRadioStartEndData sets To", () => {
|
||||
store.setActivityRadioStartEndData("taskB", "To");
|
||||
expect(store.activityRadioData.task[1]).toBe("taskB");
|
||||
});
|
||||
|
||||
it('setActivityRadioStartEndData ignores unknown', () => {
|
||||
store.setActivityRadioStartEndData('taskC', 'Unknown');
|
||||
expect(store.activityRadioData.task).toEqual(['', '']);
|
||||
it("setActivityRadioStartEndData ignores unknown", () => {
|
||||
store.setActivityRadioStartEndData("taskC", "Unknown");
|
||||
expect(store.activityRadioData.task).toEqual(["", ""]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,26 +3,32 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { useCytoscapeStore } from '@/stores/cytoscapeStore';
|
||||
import { SAVE_KEY_NAME } from '@/constants/constants.js';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { useCytoscapeStore } from "@/stores/cytoscapeStore";
|
||||
import { SAVE_KEY_NAME } from "@/constants/constants.js";
|
||||
|
||||
// Mock localStorage since jsdom's localStorage is limited
|
||||
const localStorageMock = (() => {
|
||||
let store = {};
|
||||
return {
|
||||
getItem: vi.fn((key) => store[key] || null),
|
||||
setItem: vi.fn((key, value) => { store[key] = value; }),
|
||||
removeItem: vi.fn((key) => { delete store[key]; }),
|
||||
clear: vi.fn(() => { store = {}; }),
|
||||
setItem: vi.fn((key, value) => {
|
||||
store[key] = value;
|
||||
}),
|
||||
removeItem: vi.fn((key) => {
|
||||
delete store[key];
|
||||
}),
|
||||
clear: vi.fn(() => {
|
||||
store = {};
|
||||
}),
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
Object.defineProperty(globalThis, "localStorage", {
|
||||
value: localStorageMock,
|
||||
});
|
||||
|
||||
describe('cytoscapeStore', () => {
|
||||
describe("cytoscapeStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -32,25 +38,25 @@ describe('cytoscapeStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.nodePositions).toEqual({});
|
||||
expect(store.currentGraphId).toBe('');
|
||||
expect(store.currentGraphId).toBe("");
|
||||
});
|
||||
|
||||
it('setCurrentGraphId initializes graph structure', () => {
|
||||
store.setCurrentGraphId('graph1');
|
||||
expect(store.currentGraphId).toBe('graph1');
|
||||
expect(store.nodePositions['graph1']).toEqual({
|
||||
it("setCurrentGraphId initializes graph structure", () => {
|
||||
store.setCurrentGraphId("graph1");
|
||||
expect(store.currentGraphId).toBe("graph1");
|
||||
expect(store.nodePositions["graph1"]).toEqual({
|
||||
TB: [],
|
||||
LR: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('saveNodePosition adds node and saves to localStorage', () => {
|
||||
store.setCurrentGraphId('graph1');
|
||||
store.saveNodePosition('node1', { x: 10, y: 20 }, 'TB');
|
||||
expect(store.nodePositions['graph1']['TB']).toEqual([
|
||||
{ id: 'node1', position: { x: 10, y: 20 } },
|
||||
it("saveNodePosition adds node and saves to localStorage", () => {
|
||||
store.setCurrentGraphId("graph1");
|
||||
store.saveNodePosition("node1", { x: 10, y: 20 }, "TB");
|
||||
expect(store.nodePositions["graph1"]["TB"]).toEqual([
|
||||
{ id: "node1", position: { x: 10, y: 20 } },
|
||||
]);
|
||||
expect(localStorageMock.setItem).toHaveBeenCalledWith(
|
||||
SAVE_KEY_NAME,
|
||||
@@ -58,26 +64,28 @@ describe('cytoscapeStore', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('saveNodePosition updates existing node position', () => {
|
||||
store.setCurrentGraphId('graph1');
|
||||
store.saveNodePosition('node1', { x: 10, y: 20 }, 'TB');
|
||||
store.saveNodePosition('node1', { x: 30, y: 40 }, 'TB');
|
||||
expect(store.nodePositions['graph1']['TB']).toHaveLength(1);
|
||||
expect(store.nodePositions['graph1']['TB'][0].position)
|
||||
.toEqual({ x: 30, y: 40 });
|
||||
it("saveNodePosition updates existing node position", () => {
|
||||
store.setCurrentGraphId("graph1");
|
||||
store.saveNodePosition("node1", { x: 10, y: 20 }, "TB");
|
||||
store.saveNodePosition("node1", { x: 30, y: 40 }, "TB");
|
||||
expect(store.nodePositions["graph1"]["TB"]).toHaveLength(1);
|
||||
expect(store.nodePositions["graph1"]["TB"][0].position).toEqual({
|
||||
x: 30,
|
||||
y: 40,
|
||||
});
|
||||
});
|
||||
|
||||
it('loadPositionsFromStorage restores from localStorage', () => {
|
||||
it("loadPositionsFromStorage restores from localStorage", () => {
|
||||
const data = {
|
||||
graph1: {
|
||||
TB: [{ id: 'n1', position: { x: 5, y: 10 } }],
|
||||
TB: [{ id: "n1", position: { x: 5, y: 10 } }],
|
||||
},
|
||||
};
|
||||
localStorageMock.getItem.mockReturnValue(JSON.stringify(data));
|
||||
store.setCurrentGraphId('graph1');
|
||||
store.loadPositionsFromStorage('TB');
|
||||
expect(store.nodePositions['graph1']['TB']).toEqual([
|
||||
{ id: 'n1', position: { x: 5, y: 10 } },
|
||||
store.setCurrentGraphId("graph1");
|
||||
store.loadPositionsFromStorage("TB");
|
||||
expect(store.nodePositions["graph1"]["TB"]).toEqual([
|
||||
{ id: "n1", position: { x: 5, y: 10 } },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,39 +3,42 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/06
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
// Mock modules that have deep import chains (router, Swal, pinia, toast)
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/module/alertModal.js', () => ({
|
||||
vi.mock("@/module/alertModal.js", () => ({
|
||||
uploadFailedFirst: vi.fn(),
|
||||
uploadFailedSecond: vi.fn(),
|
||||
uploadloader: vi.fn(),
|
||||
uploadSuccess: vi.fn(),
|
||||
deleteSuccess: vi.fn(),
|
||||
}));
|
||||
vi.mock('sweetalert2', () => ({
|
||||
vi.mock("sweetalert2", () => ({
|
||||
default: { close: vi.fn(), fire: vi.fn() },
|
||||
}));
|
||||
// Prevent module-level store init in cytoscapeMap.js (loaded via router → Map.vue)
|
||||
vi.mock('@/module/cytoscapeMap.js', () => ({}));
|
||||
vi.mock('@/router/index.ts', () => ({
|
||||
default: { push: vi.fn(), currentRoute: { value: { path: '/' } } },
|
||||
vi.mock("@/module/cytoscapeMap.js", () => ({}));
|
||||
vi.mock("@/router/index.ts", () => ({
|
||||
default: { push: vi.fn(), currentRoute: { value: { path: "/" } } },
|
||||
}));
|
||||
|
||||
const { mockGet, mockPost, mockPut, mockDelete } = vi.hoisted(() => ({
|
||||
mockGet: vi.fn(), mockPost: vi.fn(), mockPut: vi.fn(), mockDelete: vi.fn(),
|
||||
mockGet: vi.fn(),
|
||||
mockPost: vi.fn(),
|
||||
mockPut: vi.fn(),
|
||||
mockDelete: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockGet, post: mockPost, put: mockPut, delete: mockDelete },
|
||||
}));
|
||||
|
||||
import { useFilesStore } from '@/stores/files';
|
||||
import { useFilesStore } from "@/stores/files";
|
||||
|
||||
describe('filesStore', () => {
|
||||
describe("filesStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -45,45 +48,45 @@ describe('filesStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
expect(store.filesTag).toBe('ALL');
|
||||
it("has correct default state", () => {
|
||||
expect(store.filesTag).toBe("ALL");
|
||||
expect(store.httpStatus).toBe(200);
|
||||
expect(store.uploadId).toBeNull();
|
||||
});
|
||||
|
||||
describe('allFiles getter', () => {
|
||||
it('filters files by current filesTag', () => {
|
||||
describe("allFiles getter", () => {
|
||||
it("filters files by current filesTag", () => {
|
||||
store.allEventFiles = [
|
||||
{ fileType: 'Log', name: 'a.xes' },
|
||||
{ fileType: 'Filter', name: 'b' },
|
||||
{ fileType: 'Design', name: 'c' },
|
||||
{ fileType: "Log", name: "a.xes" },
|
||||
{ fileType: "Filter", name: "b" },
|
||||
{ fileType: "Design", name: "c" },
|
||||
];
|
||||
|
||||
store.filesTag = 'COMPARE';
|
||||
expect(store.allFiles.map((f) => f.name)).toEqual(['a.xes', 'b']);
|
||||
store.filesTag = "COMPARE";
|
||||
expect(store.allFiles.map((f) => f.name)).toEqual(["a.xes", "b"]);
|
||||
|
||||
store.filesTag = 'ALL';
|
||||
store.filesTag = "ALL";
|
||||
expect(store.allFiles).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchAllFiles', () => {
|
||||
it('fetches and transforms file data', async () => {
|
||||
describe("fetchAllFiles", () => {
|
||||
it("fetches and transforms file data", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
type: 'log',
|
||||
name: 'test.xes',
|
||||
owner: { name: 'Alice' },
|
||||
updated_at: '2024-01-15T10:00:00Z',
|
||||
accessed_at: '2024-01-15T11:00:00Z',
|
||||
type: "log",
|
||||
name: "test.xes",
|
||||
owner: { name: "Alice" },
|
||||
updated_at: "2024-01-15T10:00:00Z",
|
||||
accessed_at: "2024-01-15T11:00:00Z",
|
||||
},
|
||||
{
|
||||
type: 'filter',
|
||||
name: 'filter1',
|
||||
parent: { name: 'test.xes' },
|
||||
owner: { name: 'Bob' },
|
||||
updated_at: '2024-01-16T10:00:00Z',
|
||||
type: "filter",
|
||||
name: "filter1",
|
||||
parent: { name: "test.xes" },
|
||||
owner: { name: "Bob" },
|
||||
updated_at: "2024-01-16T10:00:00Z",
|
||||
accessed_at: null,
|
||||
},
|
||||
],
|
||||
@@ -91,36 +94,36 @@ describe('filesStore', () => {
|
||||
|
||||
await store.fetchAllFiles();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/files');
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/files");
|
||||
expect(store.allEventFiles).toHaveLength(2);
|
||||
expect(store.allEventFiles[0].fileType).toBe('Log');
|
||||
expect(store.allEventFiles[0].icon).toBe('work_history');
|
||||
expect(store.allEventFiles[0].ownerName).toBe('Alice');
|
||||
expect(store.allEventFiles[1].fileType).toBe('Filter');
|
||||
expect(store.allEventFiles[1].parentLog).toBe('test.xes');
|
||||
expect(store.allEventFiles[0].fileType).toBe("Log");
|
||||
expect(store.allEventFiles[0].icon).toBe("work_history");
|
||||
expect(store.allEventFiles[0].ownerName).toBe("Alice");
|
||||
expect(store.allEventFiles[1].fileType).toBe("Filter");
|
||||
expect(store.allEventFiles[1].parentLog).toBe("test.xes");
|
||||
expect(store.allEventFiles[1].accessed_at).toBeNull();
|
||||
});
|
||||
|
||||
it('does not throw on API failure', async () => {
|
||||
mockGet.mockRejectedValue(new Error('Network error'));
|
||||
it("does not throw on API failure", async () => {
|
||||
mockGet.mockRejectedValue(new Error("Network error"));
|
||||
await expect(store.fetchAllFiles()).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps design files without leaking metadata from previous file items', async () => {
|
||||
it("maps design files without leaking metadata from previous file items", async () => {
|
||||
mockGet.mockResolvedValue({
|
||||
data: [
|
||||
{
|
||||
type: 'log',
|
||||
name: 'order-log',
|
||||
owner: { name: 'Alice' },
|
||||
updated_at: '2024-01-15T10:00:00Z',
|
||||
type: "log",
|
||||
name: "order-log",
|
||||
owner: { name: "Alice" },
|
||||
updated_at: "2024-01-15T10:00:00Z",
|
||||
accessed_at: null,
|
||||
},
|
||||
{
|
||||
type: 'design',
|
||||
name: 'diagram-a',
|
||||
owner: { name: 'Bob' },
|
||||
updated_at: '2024-01-16T10:00:00Z',
|
||||
type: "design",
|
||||
name: "diagram-a",
|
||||
owner: { name: "Bob" },
|
||||
updated_at: "2024-01-16T10:00:00Z",
|
||||
accessed_at: null,
|
||||
},
|
||||
],
|
||||
@@ -128,123 +131,121 @@ describe('filesStore', () => {
|
||||
|
||||
await store.fetchAllFiles();
|
||||
|
||||
expect(store.allEventFiles[1].icon).toBe('shape_line');
|
||||
expect(store.allEventFiles[1].fileType).toBe('Design');
|
||||
expect(store.allEventFiles[1].parentLog).toBe('diagram-a');
|
||||
expect(store.allEventFiles[1].icon).toBe("shape_line");
|
||||
expect(store.allEventFiles[1].fileType).toBe("Design");
|
||||
expect(store.allEventFiles[1].parentLog).toBe("diagram-a");
|
||||
});
|
||||
});
|
||||
|
||||
describe('upload', () => {
|
||||
it('uploads file and navigates to Upload page', async () => {
|
||||
describe("upload", () => {
|
||||
it("uploads file and navigates to Upload page", async () => {
|
||||
mockPost.mockResolvedValue({ data: { id: 42 } });
|
||||
const formData = new FormData();
|
||||
|
||||
await store.upload(formData);
|
||||
|
||||
expect(mockPost).toHaveBeenCalledWith(
|
||||
'/api/logs/csv-uploads',
|
||||
"/api/logs/csv-uploads",
|
||||
formData,
|
||||
expect.objectContaining({
|
||||
headers: { 'Content-Type': 'multipart/form-data' },
|
||||
headers: { "Content-Type": "multipart/form-data" },
|
||||
}),
|
||||
);
|
||||
expect(store.uploadId).toBe(42);
|
||||
expect(store.$router.push).toHaveBeenCalledWith({ name: 'Upload' });
|
||||
expect(store.$router.push).toHaveBeenCalledWith({ name: "Upload" });
|
||||
});
|
||||
});
|
||||
|
||||
describe('getUploadDetail', () => {
|
||||
it('fetches upload preview', async () => {
|
||||
describe("getUploadDetail", () => {
|
||||
it("fetches upload preview", async () => {
|
||||
store.uploadId = 10;
|
||||
mockGet.mockResolvedValue({
|
||||
data: { preview: { columns: ['a', 'b'] } },
|
||||
data: { preview: { columns: ["a", "b"] } },
|
||||
});
|
||||
|
||||
await store.getUploadDetail();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/logs/csv-uploads/10');
|
||||
expect(store.allUploadDetail).toEqual({ columns: ['a', 'b'] });
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/logs/csv-uploads/10");
|
||||
expect(store.allUploadDetail).toEqual({ columns: ["a", "b"] });
|
||||
});
|
||||
});
|
||||
|
||||
describe('rename', () => {
|
||||
it('renames a log file', async () => {
|
||||
describe("rename", () => {
|
||||
it("renames a log file", async () => {
|
||||
mockPut.mockResolvedValue({});
|
||||
mockGet.mockResolvedValue({ data: [] });
|
||||
|
||||
await store.rename('log', 5, 'new-name');
|
||||
await store.rename("log", 5, "new-name");
|
||||
|
||||
expect(mockPut).toHaveBeenCalledWith('/api/logs/5/name', {
|
||||
name: 'new-name',
|
||||
expect(mockPut).toHaveBeenCalledWith("/api/logs/5/name", {
|
||||
name: "new-name",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDependents', () => {
|
||||
it('fetches dependents for a log', async () => {
|
||||
describe("getDependents", () => {
|
||||
it("fetches dependents for a log", async () => {
|
||||
mockGet.mockResolvedValue({ data: [{ id: 1 }, { id: 2 }] });
|
||||
|
||||
await store.getDependents('log', 7);
|
||||
await store.getDependents("log", 7);
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/logs/7/dependents');
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/logs/7/dependents");
|
||||
expect(store.allDependentsData).toEqual([{ id: 1 }, { id: 2 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteFile', () => {
|
||||
it('calls mockDelete before fetchAllFiles', async () => {
|
||||
describe("deleteFile", () => {
|
||||
it("calls mockDelete before fetchAllFiles", async () => {
|
||||
const callOrder = [];
|
||||
mockDelete.mockImplementation(async () => {
|
||||
callOrder.push('delete');
|
||||
callOrder.push("delete");
|
||||
return {};
|
||||
});
|
||||
mockGet.mockImplementation(async () => {
|
||||
callOrder.push('get');
|
||||
callOrder.push("get");
|
||||
return { data: [] };
|
||||
});
|
||||
|
||||
await store.deleteFile('log', 1);
|
||||
await store.deleteFile("log", 1);
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith('/api/logs/1');
|
||||
expect(callOrder.indexOf('delete')).toBeLessThan(
|
||||
callOrder.indexOf('get'),
|
||||
expect(mockDelete).toHaveBeenCalledWith("/api/logs/1");
|
||||
expect(callOrder.indexOf("delete")).toBeLessThan(
|
||||
callOrder.indexOf("get"),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns early for invalid id without throwing', async () => {
|
||||
await expect(
|
||||
store.deleteFile('log', null),
|
||||
).resolves.toBeUndefined();
|
||||
it("returns early for invalid id without throwing", async () => {
|
||||
await expect(store.deleteFile("log", null)).resolves.toBeUndefined();
|
||||
|
||||
expect(mockDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('deletionRecord', () => {
|
||||
it('deletes a deletion record', async () => {
|
||||
describe("deletionRecord", () => {
|
||||
it("deletes a deletion record", async () => {
|
||||
mockDelete.mockResolvedValue({});
|
||||
|
||||
await store.deletionRecord(5);
|
||||
|
||||
expect(mockDelete).toHaveBeenCalledWith('/api/deletion/5');
|
||||
expect(mockDelete).toHaveBeenCalledWith("/api/deletion/5");
|
||||
});
|
||||
});
|
||||
|
||||
describe('downloadFileCSV', () => {
|
||||
it('downloads CSV for a log', async () => {
|
||||
mockGet.mockResolvedValue({ data: 'col1,col2\na,b' });
|
||||
describe("downloadFileCSV", () => {
|
||||
it("downloads CSV for a log", async () => {
|
||||
mockGet.mockResolvedValue({ data: "col1,col2\na,b" });
|
||||
|
||||
window.URL.createObjectURL = vi.fn().mockReturnValue('blob:test');
|
||||
window.URL.createObjectURL = vi.fn().mockReturnValue("blob:test");
|
||||
window.URL.revokeObjectURL = vi.fn();
|
||||
|
||||
await store.downloadFileCSV('log', 3, 'my-file');
|
||||
await store.downloadFileCSV("log", 3, "my-file");
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith('/api/logs/3/csv');
|
||||
expect(window.URL.revokeObjectURL).toHaveBeenCalledWith('blob:test');
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/logs/3/csv");
|
||||
expect(window.URL.revokeObjectURL).toHaveBeenCalledWith("blob:test");
|
||||
});
|
||||
|
||||
it('returns early for unsupported type', async () => {
|
||||
await store.downloadFileCSV('log-check', 3, 'file');
|
||||
it("returns early for unsupported type", async () => {
|
||||
await store.downloadFileCSV("log-check", 3, "file");
|
||||
|
||||
expect(mockGet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { useLoadingStore } from '@/stores/loading';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { useLoadingStore } from "@/stores/loading";
|
||||
|
||||
describe('loadingStore', () => {
|
||||
describe("loadingStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -15,16 +15,16 @@ describe('loadingStore', () => {
|
||||
store = useLoadingStore();
|
||||
});
|
||||
|
||||
it('has isLoading true by default', () => {
|
||||
it("has isLoading true by default", () => {
|
||||
expect(store.isLoading).toBe(true);
|
||||
});
|
||||
|
||||
it('setIsLoading sets to false', () => {
|
||||
it("setIsLoading sets to false", () => {
|
||||
store.setIsLoading(false);
|
||||
expect(store.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
it('setIsLoading sets to true', () => {
|
||||
it("setIsLoading sets to true", () => {
|
||||
store.setIsLoading(false);
|
||||
store.setIsLoading(true);
|
||||
expect(store.isLoading).toBe(true);
|
||||
|
||||
@@ -3,27 +3,27 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
// Mock apiError to prevent side effects (imports router, pinia, toast)
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
import axios from 'axios';
|
||||
import axios from "axios";
|
||||
|
||||
const { mockClientGet } = vi.hoisted(() => ({ mockClientGet: vi.fn() }));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockClientGet },
|
||||
}));
|
||||
|
||||
import { useLoginStore } from '@/stores/login';
|
||||
import { useLoginStore } from "@/stores/login";
|
||||
|
||||
// Mock axios methods (used for signIn/refreshToken which call plain axios)
|
||||
vi.spyOn(axios, 'post').mockImplementation(vi.fn());
|
||||
vi.spyOn(axios, "post").mockImplementation(vi.fn());
|
||||
|
||||
describe('loginStore', () => {
|
||||
describe("loginStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -32,106 +32,106 @@ describe('loginStore', () => {
|
||||
store.$router = { push: vi.fn() };
|
||||
vi.clearAllMocks();
|
||||
// Clear cookies
|
||||
document.cookie.split(';').forEach((c) => {
|
||||
const name = c.split('=')[0].trim();
|
||||
document.cookie.split(";").forEach((c) => {
|
||||
const name = c.split("=")[0].trim();
|
||||
if (name) {
|
||||
document.cookie = name + '=; Max-Age=-99999999; path=/';
|
||||
document.cookie = name + "=; Max-Age=-99999999; path=/";
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
expect(store.auth.grant_type).toBe('password');
|
||||
expect(store.auth.username).toBe('');
|
||||
it("has correct default state", () => {
|
||||
expect(store.auth.grant_type).toBe("password");
|
||||
expect(store.auth.username).toBe("");
|
||||
expect(store.isLoggedIn).toBe(false);
|
||||
expect(store.isInvalid).toBe(false);
|
||||
});
|
||||
|
||||
describe('signIn', () => {
|
||||
it('stores token and navigates on success', async () => {
|
||||
describe("signIn", () => {
|
||||
it("stores token and navigates on success", async () => {
|
||||
axios.post.mockResolvedValue({
|
||||
data: {
|
||||
access_token: 'test-access-token',
|
||||
refresh_token: 'test-refresh-token',
|
||||
access_token: "test-access-token",
|
||||
refresh_token: "test-refresh-token",
|
||||
},
|
||||
});
|
||||
|
||||
await store.signIn();
|
||||
|
||||
expect(axios.post).toHaveBeenCalledWith(
|
||||
'/api/oauth/token',
|
||||
"/api/oauth/token",
|
||||
store.auth,
|
||||
expect.objectContaining({
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
}),
|
||||
);
|
||||
expect(store.isLoggedIn).toBe(true);
|
||||
// Verify token cookie was set with Secure flag
|
||||
// (jsdom drops Secure cookies, so spy on setter)
|
||||
const cookieSetter = vi.spyOn(document, 'cookie', 'set');
|
||||
const cookieSetter = vi.spyOn(document, "cookie", "set");
|
||||
vi.clearAllMocks();
|
||||
axios.post.mockResolvedValue({
|
||||
data: {
|
||||
access_token: 'test-access-token',
|
||||
refresh_token: 'test-refresh-token',
|
||||
access_token: "test-access-token",
|
||||
refresh_token: "test-refresh-token",
|
||||
},
|
||||
});
|
||||
await store.signIn();
|
||||
const tokenCall = cookieSetter.mock.calls.find(
|
||||
(c) => c[0].includes('luciaToken='),
|
||||
const tokenCall = cookieSetter.mock.calls.find((c) =>
|
||||
c[0].includes("luciaToken="),
|
||||
);
|
||||
expect(tokenCall).toBeDefined();
|
||||
expect(tokenCall[0]).toContain('Secure');
|
||||
expect(tokenCall[0]).toContain("Secure");
|
||||
cookieSetter.mockRestore();
|
||||
expect(store.$router.push).toHaveBeenCalledWith('/files');
|
||||
expect(store.$router.push).toHaveBeenCalledWith("/files");
|
||||
});
|
||||
|
||||
it('redirects to remembered URL when set', async () => {
|
||||
it("redirects to remembered URL when set", async () => {
|
||||
axios.post.mockResolvedValue({
|
||||
data: {
|
||||
access_token: 'token',
|
||||
refresh_token: 'refresh',
|
||||
access_token: "token",
|
||||
refresh_token: "refresh",
|
||||
},
|
||||
});
|
||||
// btoa('/dashboard') = 'L2Rhc2hib2FyZA=='
|
||||
store.rememberedReturnToUrl = btoa('/dashboard');
|
||||
store.rememberedReturnToUrl = btoa("/dashboard");
|
||||
|
||||
// Mock window.location.href setter
|
||||
const originalLocation = window.location;
|
||||
delete window.location;
|
||||
window.location = { href: '' };
|
||||
window.location = { href: "" };
|
||||
|
||||
await store.signIn();
|
||||
|
||||
expect(window.location.href).toBe('/dashboard');
|
||||
expect(window.location.href).toBe("/dashboard");
|
||||
window.location = originalLocation;
|
||||
});
|
||||
|
||||
it('does not redirect to external URL (open redirect prevention)', async () => {
|
||||
it("does not redirect to external URL (open redirect prevention)", async () => {
|
||||
axios.post.mockResolvedValue({
|
||||
data: {
|
||||
access_token: 'token',
|
||||
refresh_token: 'refresh',
|
||||
access_token: "token",
|
||||
refresh_token: "refresh",
|
||||
},
|
||||
});
|
||||
// Attacker crafts a return-to URL pointing to an external site
|
||||
store.rememberedReturnToUrl = btoa('https://evil.example.com/steal');
|
||||
store.rememberedReturnToUrl = btoa("https://evil.example.com/steal");
|
||||
|
||||
const originalLocation = window.location;
|
||||
delete window.location;
|
||||
window.location = { href: '' };
|
||||
window.location = { href: "" };
|
||||
|
||||
await store.signIn();
|
||||
|
||||
// Should NOT redirect to the external URL
|
||||
expect(window.location.href).not.toBe('https://evil.example.com/steal');
|
||||
expect(window.location.href).not.toBe("https://evil.example.com/steal");
|
||||
// Should fall back to /files
|
||||
expect(store.$router.push).toHaveBeenCalledWith('/files');
|
||||
expect(store.$router.push).toHaveBeenCalledWith("/files");
|
||||
window.location = originalLocation;
|
||||
});
|
||||
|
||||
it('sets isInvalid on error', async () => {
|
||||
axios.post.mockRejectedValue(new Error('401'));
|
||||
it("sets isInvalid on error", async () => {
|
||||
axios.post.mockRejectedValue(new Error("401"));
|
||||
|
||||
await store.signIn();
|
||||
|
||||
@@ -139,34 +139,34 @@ describe('loginStore', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('logOut', () => {
|
||||
it('clears auth state and navigates to login', () => {
|
||||
describe("logOut", () => {
|
||||
it("clears auth state and navigates to login", () => {
|
||||
store.isLoggedIn = true;
|
||||
store.logOut();
|
||||
|
||||
expect(store.isLoggedIn).toBe(false);
|
||||
expect(store.$router.push).toHaveBeenCalledWith('/login');
|
||||
expect(store.$router.push).toHaveBeenCalledWith("/login");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getUserData', () => {
|
||||
it('stores user data on success', async () => {
|
||||
describe("getUserData", () => {
|
||||
it("stores user data on success", async () => {
|
||||
mockClientGet.mockResolvedValue({
|
||||
data: { username: 'testuser', name: 'Test User' },
|
||||
data: { username: "testuser", name: "Test User" },
|
||||
});
|
||||
|
||||
await store.getUserData();
|
||||
|
||||
expect(mockClientGet).toHaveBeenCalledWith('/api/my-account');
|
||||
expect(mockClientGet).toHaveBeenCalledWith("/api/my-account");
|
||||
expect(store.userData).toEqual({
|
||||
username: 'testuser',
|
||||
name: 'Test User',
|
||||
username: "testuser",
|
||||
name: "Test User",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkLogin', () => {
|
||||
it('does not redirect on success', async () => {
|
||||
describe("checkLogin", () => {
|
||||
it("does not redirect on success", async () => {
|
||||
mockClientGet.mockResolvedValue({ data: {} });
|
||||
|
||||
await store.checkLogin();
|
||||
@@ -174,34 +174,34 @@ describe('loginStore', () => {
|
||||
expect(store.$router.push).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to login on error', async () => {
|
||||
mockClientGet.mockRejectedValue(new Error('401'));
|
||||
it("redirects to login on error", async () => {
|
||||
mockClientGet.mockRejectedValue(new Error("401"));
|
||||
|
||||
await store.checkLogin();
|
||||
|
||||
expect(store.$router.push).toHaveBeenCalledWith('/login');
|
||||
expect(store.$router.push).toHaveBeenCalledWith("/login");
|
||||
});
|
||||
});
|
||||
|
||||
it('setRememberedReturnToUrl stores URL', () => {
|
||||
store.setRememberedReturnToUrl('abc');
|
||||
expect(store.rememberedReturnToUrl).toBe('abc');
|
||||
it("setRememberedReturnToUrl stores URL", () => {
|
||||
store.setRememberedReturnToUrl("abc");
|
||||
expect(store.rememberedReturnToUrl).toBe("abc");
|
||||
});
|
||||
|
||||
it('setIsLoggedIn sets boolean', () => {
|
||||
it("setIsLoggedIn sets boolean", () => {
|
||||
store.setIsLoggedIn(true);
|
||||
expect(store.isLoggedIn).toBe(true);
|
||||
});
|
||||
|
||||
describe('refreshToken', () => {
|
||||
it('sends request with correct config and updates tokens on success', async () => {
|
||||
document.cookie = 'luciaRefreshToken=old-refresh-token';
|
||||
describe("refreshToken", () => {
|
||||
it("sends request with correct config and updates tokens on success", async () => {
|
||||
document.cookie = "luciaRefreshToken=old-refresh-token";
|
||||
|
||||
axios.post.mockResolvedValue({
|
||||
status: 200,
|
||||
data: {
|
||||
access_token: 'new-access-token',
|
||||
refresh_token: 'new-refresh-token',
|
||||
access_token: "new-access-token",
|
||||
refresh_token: "new-refresh-token",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -209,44 +209,43 @@ describe('loginStore', () => {
|
||||
|
||||
// Should call with content-type header (config must be defined)
|
||||
expect(axios.post).toHaveBeenCalledWith(
|
||||
'/api/oauth/token',
|
||||
"/api/oauth/token",
|
||||
expect.objectContaining({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: 'old-refresh-token',
|
||||
grant_type: "refresh_token",
|
||||
refresh_token: "old-refresh-token",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
}),
|
||||
);
|
||||
|
||||
// Verify cookies were set with Secure flag
|
||||
const cookieSetter = vi.spyOn(document, 'cookie', 'set');
|
||||
const cookieSetter = vi.spyOn(document, "cookie", "set");
|
||||
vi.clearAllMocks();
|
||||
document.cookie = 'luciaRefreshToken=old-refresh-token';
|
||||
document.cookie = "luciaRefreshToken=old-refresh-token";
|
||||
axios.post.mockResolvedValue({
|
||||
status: 200,
|
||||
data: {
|
||||
access_token: 'new-access-token',
|
||||
refresh_token: 'new-refresh-token',
|
||||
access_token: "new-access-token",
|
||||
refresh_token: "new-refresh-token",
|
||||
},
|
||||
});
|
||||
await store.refreshToken();
|
||||
const tokenCall = cookieSetter.mock.calls.find(
|
||||
(c) => c[0].includes('luciaToken='),
|
||||
const tokenCall = cookieSetter.mock.calls.find((c) =>
|
||||
c[0].includes("luciaToken="),
|
||||
);
|
||||
expect(tokenCall).toBeDefined();
|
||||
expect(tokenCall[0]).toContain('Secure');
|
||||
expect(tokenCall[0]).toContain("Secure");
|
||||
cookieSetter.mockRestore();
|
||||
});
|
||||
|
||||
it('redirects to login and re-throws on failure', async () => {
|
||||
document.cookie = 'luciaRefreshToken=old-refresh-token';
|
||||
axios.post.mockRejectedValue(new Error('401'));
|
||||
it("redirects to login and re-throws on failure", async () => {
|
||||
document.cookie = "luciaRefreshToken=old-refresh-token";
|
||||
axios.post.mockRejectedValue(new Error("401"));
|
||||
|
||||
await expect(store.refreshToken()).rejects.toThrow('401');
|
||||
await expect(store.refreshToken()).rejects.toThrow("401");
|
||||
|
||||
expect(store.$router.push).toHaveBeenCalledWith('/login');
|
||||
expect(store.$router.push).toHaveBeenCalledWith("/login");
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { useMapCompareStore } from '@/stores/mapCompareStore';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { useMapCompareStore } from "@/stores/mapCompareStore";
|
||||
|
||||
describe('mapCompareStore', () => {
|
||||
describe("mapCompareStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -15,22 +15,22 @@ describe('mapCompareStore', () => {
|
||||
store = useMapCompareStore();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.routeParam).toEqual({
|
||||
primaryType: '',
|
||||
primaryId: '',
|
||||
secondaryType: '',
|
||||
secondaryId: '',
|
||||
primaryType: "",
|
||||
primaryId: "",
|
||||
secondaryType: "",
|
||||
secondaryId: "",
|
||||
});
|
||||
});
|
||||
|
||||
it('setCompareRouteParam sets all params', () => {
|
||||
store.setCompareRouteParam('log', '1', 'filter', '2');
|
||||
it("setCompareRouteParam sets all params", () => {
|
||||
store.setCompareRouteParam("log", "1", "filter", "2");
|
||||
expect(store.routeParam).toEqual({
|
||||
primaryType: 'log',
|
||||
primaryId: '1',
|
||||
secondaryType: 'filter',
|
||||
secondaryId: '2',
|
||||
primaryType: "log",
|
||||
primaryId: "1",
|
||||
secondaryType: "filter",
|
||||
secondaryId: "2",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,31 +3,31 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/06
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
// Mock allMapData store (used by createInsightWithPath / createPaths)
|
||||
vi.mock('@/stores/allMapData', () => ({
|
||||
vi.mock("@/stores/allMapData", () => ({
|
||||
default: () => ({ insights: {} }),
|
||||
}));
|
||||
|
||||
// Mock SVG asset imports
|
||||
vi.mock('@/assets/capsule1-glow.svg', () => ({ default: 'glow1' }));
|
||||
vi.mock('@/assets/capsule2-glow.svg', () => ({ default: 'glow2' }));
|
||||
vi.mock('@/assets/capsule3-glow.svg', () => ({ default: 'glow3' }));
|
||||
vi.mock('@/assets/capsule4-glow.svg', () => ({ default: 'glow4' }));
|
||||
vi.mock('@/assets/capsule1.svg', () => ({ default: 'cap1' }));
|
||||
vi.mock('@/assets/capsule2.svg', () => ({ default: 'cap2' }));
|
||||
vi.mock('@/assets/capsule3.svg', () => ({ default: 'cap3' }));
|
||||
vi.mock('@/assets/capsule4.svg', () => ({ default: 'cap4' }));
|
||||
vi.mock("@/assets/capsule1-glow.svg", () => ({ default: "glow1" }));
|
||||
vi.mock("@/assets/capsule2-glow.svg", () => ({ default: "glow2" }));
|
||||
vi.mock("@/assets/capsule3-glow.svg", () => ({ default: "glow3" }));
|
||||
vi.mock("@/assets/capsule4-glow.svg", () => ({ default: "glow4" }));
|
||||
vi.mock("@/assets/capsule1.svg", () => ({ default: "cap1" }));
|
||||
vi.mock("@/assets/capsule2.svg", () => ({ default: "cap2" }));
|
||||
vi.mock("@/assets/capsule3.svg", () => ({ default: "cap3" }));
|
||||
vi.mock("@/assets/capsule4.svg", () => ({ default: "cap4" }));
|
||||
|
||||
import { useMapPathStore } from '@/stores/mapPathStore';
|
||||
import { useMapPathStore } from "@/stores/mapPathStore";
|
||||
|
||||
/**
|
||||
* Creates a mock Cytoscape node.
|
||||
*/
|
||||
function mockNode(label, level = 0) {
|
||||
const nodeData = { label, level, nodeImageUrl: '' };
|
||||
const nodeData = { label, level, nodeImageUrl: "" };
|
||||
const classes = new Set();
|
||||
const node = {
|
||||
data: vi.fn((key, value) => {
|
||||
@@ -37,8 +37,14 @@ function mockNode(label, level = 0) {
|
||||
}
|
||||
return nodeData[key];
|
||||
}),
|
||||
addClass: vi.fn((cls) => { classes.add(cls); return node; }),
|
||||
removeClass: vi.fn((cls) => { classes.delete(cls); return node; }),
|
||||
addClass: vi.fn((cls) => {
|
||||
classes.add(cls);
|
||||
return node;
|
||||
}),
|
||||
removeClass: vi.fn((cls) => {
|
||||
classes.delete(cls);
|
||||
return node;
|
||||
}),
|
||||
hasClass: (cls) => classes.has(cls),
|
||||
outgoers: vi.fn(() => mockCollection([])),
|
||||
incomers: vi.fn(() => mockCollection([])),
|
||||
@@ -56,10 +62,16 @@ function mockNode(label, level = 0) {
|
||||
function mockEdge() {
|
||||
const classes = new Set();
|
||||
const edge = {
|
||||
addClass: vi.fn((cls) => { classes.add(cls); return edge; }),
|
||||
removeClass: vi.fn((cls) => { classes.delete(cls); return edge; }),
|
||||
source: vi.fn(() => mockNode('src')),
|
||||
target: vi.fn(() => mockNode('tgt')),
|
||||
addClass: vi.fn((cls) => {
|
||||
classes.add(cls);
|
||||
return edge;
|
||||
}),
|
||||
removeClass: vi.fn((cls) => {
|
||||
classes.delete(cls);
|
||||
return edge;
|
||||
}),
|
||||
source: vi.fn(() => mockNode("src")),
|
||||
target: vi.fn(() => mockNode("tgt")),
|
||||
_classes: classes,
|
||||
};
|
||||
return edge;
|
||||
@@ -90,7 +102,7 @@ function mockCytoscape(nodes = [], edges = []) {
|
||||
};
|
||||
}
|
||||
|
||||
describe('mapPathStore', () => {
|
||||
describe("mapPathStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -99,26 +111,26 @@ describe('mapPathStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
expect(store.processOrBPMN).toBe('process');
|
||||
expect(store.curveType).toBe('curved');
|
||||
expect(store.directionType).toBe('horizontal');
|
||||
it("has correct default state", () => {
|
||||
expect(store.processOrBPMN).toBe("process");
|
||||
expect(store.curveType).toBe("curved");
|
||||
expect(store.directionType).toBe("horizontal");
|
||||
expect(store.isBPMNOn).toBe(false);
|
||||
expect(store.allPaths).toEqual([]);
|
||||
expect(store.activeTrace).toBe(0);
|
||||
expect(store.lastClickedNode).toBeNull();
|
||||
});
|
||||
|
||||
it('setIsBPMNOn updates state', () => {
|
||||
it("setIsBPMNOn updates state", () => {
|
||||
store.setIsBPMNOn(true);
|
||||
expect(store.isBPMNOn).toBe(true);
|
||||
store.setIsBPMNOn(false);
|
||||
expect(store.isBPMNOn).toBe(false);
|
||||
});
|
||||
|
||||
describe('clearAllHighlight', () => {
|
||||
it('removes highlight classes from all nodes and edges', () => {
|
||||
const node1 = mockNode('A', 0);
|
||||
describe("clearAllHighlight", () => {
|
||||
it("removes highlight classes from all nodes and edges", () => {
|
||||
const node1 = mockNode("A", 0);
|
||||
const edge1 = mockEdge();
|
||||
const cy = mockCytoscape([node1], [edge1]);
|
||||
store.cytoscape.process.curved.horizontal = cy;
|
||||
@@ -129,15 +141,15 @@ describe('mapPathStore', () => {
|
||||
expect(cy.nodes).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not throw when cytoscape is null', () => {
|
||||
it("does not throw when cytoscape is null", () => {
|
||||
store.cytoscape.process.curved.horizontal = null;
|
||||
expect(() => store.clearAllHighlight()).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('onNodeClickHighlightEdges', () => {
|
||||
it('highlights clicked node and its edges', () => {
|
||||
const node = mockNode('Activity', 1);
|
||||
describe("onNodeClickHighlightEdges", () => {
|
||||
it("highlights clicked node and its edges", () => {
|
||||
const node = mockNode("Activity", 1);
|
||||
const outEdge = mockEdge();
|
||||
const inEdge = mockEdge();
|
||||
node.outgoers.mockReturnValue(mockCollection([outEdge]));
|
||||
@@ -147,17 +159,17 @@ describe('mapPathStore', () => {
|
||||
|
||||
store.onNodeClickHighlightEdges(node);
|
||||
|
||||
expect(node.addClass).toHaveBeenCalledWith('highlight-node');
|
||||
expect(outEdge.addClass).toHaveBeenCalledWith('highlight-edge');
|
||||
expect(inEdge.addClass).toHaveBeenCalledWith('highlight-edge');
|
||||
expect(node.addClass).toHaveBeenCalledWith("highlight-node");
|
||||
expect(outEdge.addClass).toHaveBeenCalledWith("highlight-edge");
|
||||
expect(inEdge.addClass).toHaveBeenCalledWith("highlight-edge");
|
||||
expect(store.lastClickedNode).toStrictEqual(node);
|
||||
});
|
||||
});
|
||||
|
||||
describe('onEdgeClickHighlightNodes', () => {
|
||||
it('highlights source and target nodes of clicked edge', () => {
|
||||
const src = mockNode('Start', 0);
|
||||
const tgt = mockNode('End', 2);
|
||||
describe("onEdgeClickHighlightNodes", () => {
|
||||
it("highlights source and target nodes of clicked edge", () => {
|
||||
const src = mockNode("Start", 0);
|
||||
const tgt = mockNode("End", 2);
|
||||
const edge = mockEdge();
|
||||
edge.source.mockReturnValue(src);
|
||||
edge.target.mockReturnValue(tgt);
|
||||
@@ -166,9 +178,9 @@ describe('mapPathStore', () => {
|
||||
|
||||
store.onEdgeClickHighlightNodes(edge);
|
||||
|
||||
expect(src.addClass).toHaveBeenCalledWith('highlight-node');
|
||||
expect(tgt.addClass).toHaveBeenCalledWith('highlight-node');
|
||||
expect(edge.addClass).toHaveBeenCalledWith('highlight-edge');
|
||||
expect(src.addClass).toHaveBeenCalledWith("highlight-node");
|
||||
expect(tgt.addClass).toHaveBeenCalledWith("highlight-node");
|
||||
expect(edge.addClass).toHaveBeenCalledWith("highlight-edge");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { useModalStore } from '@/stores/modal';
|
||||
import { MODAL_ACCT_INFO, MODAL_DELETE } from '@/constants/constants.js';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { useModalStore } from "@/stores/modal";
|
||||
import { MODAL_ACCT_INFO, MODAL_DELETE } from "@/constants/constants.js";
|
||||
|
||||
describe('modalStore', () => {
|
||||
describe("modalStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -16,18 +16,18 @@ describe('modalStore', () => {
|
||||
store = useModalStore();
|
||||
});
|
||||
|
||||
it('has default state', () => {
|
||||
it("has default state", () => {
|
||||
expect(store.isModalOpen).toBe(false);
|
||||
expect(store.whichModal).toBe(MODAL_ACCT_INFO);
|
||||
});
|
||||
|
||||
it('openModal sets isModalOpen and whichModal', () => {
|
||||
it("openModal sets isModalOpen and whichModal", () => {
|
||||
store.openModal(MODAL_DELETE);
|
||||
expect(store.isModalOpen).toBe(true);
|
||||
expect(store.whichModal).toBe(MODAL_DELETE);
|
||||
});
|
||||
|
||||
it('closeModal sets isModalOpen to false', async () => {
|
||||
it("closeModal sets isModalOpen to false", async () => {
|
||||
store.openModal(MODAL_DELETE);
|
||||
await store.closeModal();
|
||||
expect(store.isModalOpen).toBe(false);
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { usePageAdminStore } from '@/stores/pageAdmin';
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
import { usePageAdminStore } from "@/stores/pageAdmin";
|
||||
|
||||
describe('pageAdminStore', () => {
|
||||
describe("pageAdminStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -15,81 +15,81 @@ describe('pageAdminStore', () => {
|
||||
store = usePageAdminStore();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
expect(store.activePage).toBe('MAP');
|
||||
expect(store.previousPage).toBe('MAP');
|
||||
expect(store.pendingActivePage).toBe('FILES');
|
||||
it("has correct default state", () => {
|
||||
expect(store.activePage).toBe("MAP");
|
||||
expect(store.previousPage).toBe("MAP");
|
||||
expect(store.pendingActivePage).toBe("FILES");
|
||||
expect(store.isPagePending).toBe(false);
|
||||
expect(store.shouldKeepPreviousPage).toBe(false);
|
||||
expect(store.currentMapFile).toBe('');
|
||||
expect(store.currentMapFile).toBe("");
|
||||
});
|
||||
|
||||
it('setActivePage converts page name', () => {
|
||||
store.setActivePage('CheckConformance');
|
||||
expect(store.activePage).toBe('CONFORMANCE');
|
||||
it("setActivePage converts page name", () => {
|
||||
store.setActivePage("CheckConformance");
|
||||
expect(store.activePage).toBe("CONFORMANCE");
|
||||
});
|
||||
|
||||
it('setPreviousPage converts page name', () => {
|
||||
store.setPreviousPage('CheckPerformance');
|
||||
expect(store.previousPage).toBe('PERFORMANCE');
|
||||
it("setPreviousPage converts page name", () => {
|
||||
store.setPreviousPage("CheckPerformance");
|
||||
expect(store.previousPage).toBe("PERFORMANCE");
|
||||
});
|
||||
|
||||
it('setPreviousPageUsingActivePage copies activePage to previousPage', () => {
|
||||
store.setActivePage('CONFORMANCE');
|
||||
it("setPreviousPageUsingActivePage copies activePage to previousPage", () => {
|
||||
store.setActivePage("CONFORMANCE");
|
||||
store.setPreviousPageUsingActivePage();
|
||||
expect(store.previousPage).toBe('CONFORMANCE');
|
||||
expect(store.previousPage).toBe("CONFORMANCE");
|
||||
});
|
||||
|
||||
it('setIsPagePendingBoolean sets boolean', () => {
|
||||
it("setIsPagePendingBoolean sets boolean", () => {
|
||||
store.setIsPagePendingBoolean(true);
|
||||
expect(store.isPagePending).toBe(true);
|
||||
});
|
||||
|
||||
it('setPendingActivePage converts and sets page', () => {
|
||||
store.setPendingActivePage('CheckMap');
|
||||
expect(store.pendingActivePage).toBe('MAP');
|
||||
it("setPendingActivePage converts and sets page", () => {
|
||||
store.setPendingActivePage("CheckMap");
|
||||
expect(store.pendingActivePage).toBe("MAP");
|
||||
});
|
||||
|
||||
it('copyPendingPageToActivePage transfers value', () => {
|
||||
store.setPendingActivePage('CheckConformance');
|
||||
it("copyPendingPageToActivePage transfers value", () => {
|
||||
store.setPendingActivePage("CheckConformance");
|
||||
store.copyPendingPageToActivePage();
|
||||
expect(store.activePage).toBe('CONFORMANCE');
|
||||
expect(store.activePage).toBe("CONFORMANCE");
|
||||
});
|
||||
|
||||
it('clearPendingActivePage resets to empty', () => {
|
||||
store.setPendingActivePage('CheckMap');
|
||||
it("clearPendingActivePage resets to empty", () => {
|
||||
store.setPendingActivePage("CheckMap");
|
||||
store.clearPendingActivePage();
|
||||
expect(store.pendingActivePage).toBe('');
|
||||
expect(store.pendingActivePage).toBe("");
|
||||
});
|
||||
|
||||
it('keepPreviousPage restores previous page', () => {
|
||||
store.setPreviousPage('CONFORMANCE');
|
||||
store.setActivePage('PERFORMANCE');
|
||||
it("keepPreviousPage restores previous page", () => {
|
||||
store.setPreviousPage("CONFORMANCE");
|
||||
store.setActivePage("PERFORMANCE");
|
||||
store.keepPreviousPage();
|
||||
expect(store.activePage).toBe('CONFORMANCE');
|
||||
expect(store.activePage).toBe("CONFORMANCE");
|
||||
expect(store.shouldKeepPreviousPage).toBe(true);
|
||||
});
|
||||
|
||||
it('clearShouldKeepPreviousPageBoolean resets flag', () => {
|
||||
it("clearShouldKeepPreviousPageBoolean resets flag", () => {
|
||||
store.keepPreviousPage();
|
||||
store.clearShouldKeepPreviousPageBoolean();
|
||||
expect(store.shouldKeepPreviousPage).toBe(false);
|
||||
});
|
||||
|
||||
it('setCurrentMapFile sets file name', () => {
|
||||
store.setCurrentMapFile('test.csv');
|
||||
expect(store.currentMapFile).toBe('test.csv');
|
||||
it("setCurrentMapFile sets file name", () => {
|
||||
store.setCurrentMapFile("test.csv");
|
||||
expect(store.currentMapFile).toBe("test.csv");
|
||||
});
|
||||
|
||||
it('setActivePageComputedByRoute extracts route name', () => {
|
||||
const routeMatched = [{ name: 'CheckMap' }];
|
||||
it("setActivePageComputedByRoute extracts route name", () => {
|
||||
const routeMatched = [{ name: "CheckMap" }];
|
||||
store.setActivePageComputedByRoute(routeMatched);
|
||||
expect(store.activePageComputedByRoute).toBe('MAP');
|
||||
expect(store.activePageComputedByRoute).toBe("MAP");
|
||||
});
|
||||
|
||||
it('setActivePageComputedByRoute handles empty array', () => {
|
||||
it("setActivePageComputedByRoute handles empty array", () => {
|
||||
store.setActivePageComputedByRoute([]);
|
||||
// Should not change default value
|
||||
expect(store.activePageComputedByRoute).toBe('MAP');
|
||||
expect(store.activePageComputedByRoute).toBe("MAP");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,21 +3,21 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
|
||||
const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() }));
|
||||
vi.mock('@/api/client.js', () => ({
|
||||
vi.mock("@/api/client.js", () => ({
|
||||
default: { get: mockGet },
|
||||
}));
|
||||
|
||||
import { usePerformanceStore } from '@/stores/performance';
|
||||
import { usePerformanceStore } from "@/stores/performance";
|
||||
|
||||
describe('performanceStore', () => {
|
||||
describe("performanceStore", () => {
|
||||
let store;
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -26,62 +26,57 @@ describe('performanceStore', () => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('has correct default state', () => {
|
||||
it("has correct default state", () => {
|
||||
expect(store.allPerformanceData).toBeNull();
|
||||
expect(store.freqChartData).toBeNull();
|
||||
});
|
||||
|
||||
it('performanceData getter returns allPerformanceData', () => {
|
||||
it("performanceData getter returns allPerformanceData", () => {
|
||||
store.allPerformanceData = { time: {}, freq: {} };
|
||||
expect(store.performanceData).toEqual({ time: {}, freq: {} });
|
||||
});
|
||||
|
||||
describe('getPerformance', () => {
|
||||
it('fetches log performance data', async () => {
|
||||
describe("getPerformance", () => {
|
||||
it("fetches log performance data", async () => {
|
||||
const mockData = { time: { charts: [] }, freq: { charts: [] } };
|
||||
mockGet.mockResolvedValue({ data: mockData });
|
||||
|
||||
await store.getPerformance('log', 1);
|
||||
await store.getPerformance("log", 1);
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/logs/1/performance',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/logs/1/performance");
|
||||
expect(store.allPerformanceData).toEqual(mockData);
|
||||
});
|
||||
|
||||
it('fetches filter performance data', async () => {
|
||||
it("fetches filter performance data", async () => {
|
||||
mockGet.mockResolvedValue({ data: { time: {} } });
|
||||
|
||||
await store.getPerformance('filter', 5);
|
||||
await store.getPerformance("filter", 5);
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
'/api/filters/5/performance',
|
||||
);
|
||||
expect(mockGet).toHaveBeenCalledWith("/api/filters/5/performance");
|
||||
});
|
||||
|
||||
it('does not throw on API failure', async () => {
|
||||
mockGet.mockRejectedValue(new Error('Network error'));
|
||||
it("does not throw on API failure", async () => {
|
||||
mockGet.mockRejectedValue(new Error("Network error"));
|
||||
|
||||
// Should not throw - apiError handles it
|
||||
await expect(store.getPerformance('log', 1))
|
||||
.resolves.not.toThrow();
|
||||
await expect(store.getPerformance("log", 1)).resolves.not.toThrow();
|
||||
expect(store.allPerformanceData).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('setFreqChartData sets data', () => {
|
||||
it("setFreqChartData sets data", () => {
|
||||
const data = { labels: [], datasets: [] };
|
||||
store.setFreqChartData(data);
|
||||
expect(store.freqChartData).toEqual(data);
|
||||
});
|
||||
|
||||
it('setFreqChartOptions sets options', () => {
|
||||
it("setFreqChartOptions sets options", () => {
|
||||
const opts = { responsive: true };
|
||||
store.setFreqChartOptions(opts);
|
||||
expect(store.freqChartOptions).toEqual(opts);
|
||||
});
|
||||
|
||||
it('setFreqChartXData sets x data', () => {
|
||||
it("setFreqChartXData sets x data", () => {
|
||||
const xData = { minX: 0, maxX: 100 };
|
||||
store.setFreqChartXData(xData);
|
||||
expect(store.freqChartXData).toEqual(xData);
|
||||
|
||||
@@ -3,54 +3,53 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import abbreviateNumber from '@/module/abbreviateNumber.js';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import abbreviateNumber from "@/module/abbreviateNumber.js";
|
||||
|
||||
describe('abbreviateNumber', () => {
|
||||
describe("abbreviateNumber", () => {
|
||||
it('returns "0" for 0 seconds', () => {
|
||||
expect(abbreviateNumber(0)).toBe('0');
|
||||
expect(abbreviateNumber(0)).toBe("0");
|
||||
});
|
||||
|
||||
it('returns seconds only when < 60', () => {
|
||||
expect(abbreviateNumber(45).trim()).toBe('45s');
|
||||
it("returns seconds only when < 60", () => {
|
||||
expect(abbreviateNumber(45).trim()).toBe("45s");
|
||||
});
|
||||
|
||||
it('returns minutes and seconds', () => {
|
||||
it("returns minutes and seconds", () => {
|
||||
// 2m 30s = 150s
|
||||
expect(abbreviateNumber(150).trim()).toBe('2m 30s');
|
||||
expect(abbreviateNumber(150).trim()).toBe("2m 30s");
|
||||
});
|
||||
|
||||
it('returns hours, minutes, and seconds', () => {
|
||||
it("returns hours, minutes, and seconds", () => {
|
||||
// 1h 1m 1s = 3661s
|
||||
expect(abbreviateNumber(3661).trim()).toBe('1h 1m 1s');
|
||||
expect(abbreviateNumber(3661).trim()).toBe("1h 1m 1s");
|
||||
});
|
||||
|
||||
it('returns days, hours, minutes, and seconds', () => {
|
||||
it("returns days, hours, minutes, and seconds", () => {
|
||||
// 1d 2h 3m 4s = 93784s
|
||||
expect(abbreviateNumber(93784).trim())
|
||||
.toBe('1d 2h 3m 4s');
|
||||
expect(abbreviateNumber(93784).trim()).toBe("1d 2h 3m 4s");
|
||||
});
|
||||
|
||||
it('handles exact day boundary', () => {
|
||||
it("handles exact day boundary", () => {
|
||||
// 1d = 86400s
|
||||
expect(abbreviateNumber(86400).trim()).toBe('1d');
|
||||
expect(abbreviateNumber(86400).trim()).toBe("1d");
|
||||
});
|
||||
|
||||
it('handles exact hour boundary', () => {
|
||||
it("handles exact hour boundary", () => {
|
||||
// 1h = 3600s
|
||||
expect(abbreviateNumber(3600).trim()).toBe('1h');
|
||||
expect(abbreviateNumber(3600).trim()).toBe("1h");
|
||||
});
|
||||
|
||||
it('handles string input by parsing as int', () => {
|
||||
expect(abbreviateNumber('150').trim()).toBe('2m 30s');
|
||||
it("handles string input by parsing as int", () => {
|
||||
expect(abbreviateNumber("150").trim()).toBe("2m 30s");
|
||||
});
|
||||
|
||||
it('handles NaN input', () => {
|
||||
expect(abbreviateNumber('abc').trim()).toBe('');
|
||||
it("handles NaN input", () => {
|
||||
expect(abbreviateNumber("abc").trim()).toBe("");
|
||||
});
|
||||
|
||||
it('does not have trailing whitespace', () => {
|
||||
expect(abbreviateNumber(45)).toBe('45s');
|
||||
expect(abbreviateNumber(3661)).toBe('1h 1m 1s');
|
||||
it("does not have trailing whitespace", () => {
|
||||
expect(abbreviateNumber(45)).toBe("45s");
|
||||
expect(abbreviateNumber(3661)).toBe("1h 1m 1s");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,29 +3,29 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import numberLabel from '@/module/numberLabel.js';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import numberLabel from "@/module/numberLabel.js";
|
||||
|
||||
describe('numberLabel', () => {
|
||||
it('formats small numbers without commas', () => {
|
||||
expect(numberLabel(1)).toBe('1');
|
||||
expect(numberLabel(999)).toBe('999');
|
||||
describe("numberLabel", () => {
|
||||
it("formats small numbers without commas", () => {
|
||||
expect(numberLabel(1)).toBe("1");
|
||||
expect(numberLabel(999)).toBe("999");
|
||||
});
|
||||
|
||||
it('formats thousands with commas', () => {
|
||||
expect(numberLabel(1000)).toBe('1,000');
|
||||
expect(numberLabel(12345)).toBe('12,345');
|
||||
it("formats thousands with commas", () => {
|
||||
expect(numberLabel(1000)).toBe("1,000");
|
||||
expect(numberLabel(12345)).toBe("12,345");
|
||||
});
|
||||
|
||||
it('formats millions with commas', () => {
|
||||
expect(numberLabel(1234567)).toBe('1,234,567');
|
||||
it("formats millions with commas", () => {
|
||||
expect(numberLabel(1234567)).toBe("1,234,567");
|
||||
});
|
||||
|
||||
it('preserves decimal places', () => {
|
||||
expect(numberLabel(1234.56)).toBe('1,234.56');
|
||||
it("preserves decimal places", () => {
|
||||
expect(numberLabel(1234.56)).toBe("1,234.56");
|
||||
});
|
||||
|
||||
it('handles zero', () => {
|
||||
expect(numberLabel(0)).toBe('0');
|
||||
it("handles zero", () => {
|
||||
expect(numberLabel(0)).toBe("0");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
setLineChartData,
|
||||
setBarChartData,
|
||||
@@ -12,110 +12,115 @@ import {
|
||||
getXIndex,
|
||||
formatTime,
|
||||
formatMaxTwo,
|
||||
} from '@/module/setChartData.js';
|
||||
} from "@/module/setChartData.js";
|
||||
|
||||
describe('timeRange', () => {
|
||||
it('splits time into equal parts', () => {
|
||||
describe("timeRange", () => {
|
||||
it("splits time into equal parts", () => {
|
||||
const result = timeRange(0, 100, 3);
|
||||
expect(result).toEqual([0, 50, 100]);
|
||||
});
|
||||
|
||||
it('rounds values to integers', () => {
|
||||
it("rounds values to integers", () => {
|
||||
const result = timeRange(0, 10, 4);
|
||||
// 0, 3.33, 6.67, 10 -> rounded
|
||||
expect(result).toEqual([0, 3, 7, 10]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getXIndex', () => {
|
||||
it('finds exact match index', () => {
|
||||
describe("getXIndex", () => {
|
||||
it("finds exact match index", () => {
|
||||
expect(getXIndex([10, 20, 30], 20)).toBe(1);
|
||||
});
|
||||
|
||||
it('finds closest value index', () => {
|
||||
it("finds closest value index", () => {
|
||||
expect(getXIndex([10, 20, 30], 22)).toBe(1);
|
||||
});
|
||||
|
||||
it('returns last matching index for equal distances', () => {
|
||||
it("returns last matching index for equal distances", () => {
|
||||
// 15 is equidistant from 10 and 20, <= means last wins
|
||||
expect(getXIndex([10, 20, 30], 15)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatTime', () => {
|
||||
it('formats seconds only', () => {
|
||||
expect(formatTime(45)).toBe('45s');
|
||||
describe("formatTime", () => {
|
||||
it("formats seconds only", () => {
|
||||
expect(formatTime(45)).toBe("45s");
|
||||
});
|
||||
|
||||
it('formats minutes and seconds', () => {
|
||||
expect(formatTime(125)).toBe('2m5s');
|
||||
it("formats minutes and seconds", () => {
|
||||
expect(formatTime(125)).toBe("2m5s");
|
||||
});
|
||||
|
||||
it('formats hours, minutes, seconds', () => {
|
||||
expect(formatTime(3661)).toBe('1h1m1s');
|
||||
it("formats hours, minutes, seconds", () => {
|
||||
expect(formatTime(3661)).toBe("1h1m1s");
|
||||
});
|
||||
|
||||
it('formats days', () => {
|
||||
expect(formatTime(90061)).toBe('1d1h1m1s');
|
||||
it("formats days", () => {
|
||||
expect(formatTime(90061)).toBe("1d1h1m1s");
|
||||
});
|
||||
|
||||
it('returns null for NaN', () => {
|
||||
expect(formatTime('abc')).toBeNull();
|
||||
it("returns null for NaN", () => {
|
||||
expect(formatTime("abc")).toBeNull();
|
||||
});
|
||||
|
||||
it('handles zero seconds', () => {
|
||||
expect(formatTime(0)).toBe('0s');
|
||||
it("handles zero seconds", () => {
|
||||
expect(formatTime(0)).toBe("0s");
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatMaxTwo', () => {
|
||||
it('keeps only top two units', () => {
|
||||
expect(formatMaxTwo(['1d2h3m4s'])).toEqual(['1d 2h']);
|
||||
describe("formatMaxTwo", () => {
|
||||
it("keeps only top two units", () => {
|
||||
expect(formatMaxTwo(["1d2h3m4s"])).toEqual(["1d 2h"]);
|
||||
});
|
||||
|
||||
it('keeps single unit as-is', () => {
|
||||
expect(formatMaxTwo(['45s'])).toEqual(['45s']);
|
||||
it("keeps single unit as-is", () => {
|
||||
expect(formatMaxTwo(["45s"])).toEqual(["45s"]);
|
||||
});
|
||||
|
||||
it('handles two units', () => {
|
||||
expect(formatMaxTwo(['3m20s'])).toEqual(['3m 20s']);
|
||||
it("handles two units", () => {
|
||||
expect(formatMaxTwo(["3m20s"])).toEqual(["3m 20s"]);
|
||||
});
|
||||
|
||||
it('processes multiple items', () => {
|
||||
expect(formatMaxTwo(['1h30m10s', '45s']))
|
||||
.toEqual(['1h 30m', '45s']);
|
||||
it("processes multiple items", () => {
|
||||
expect(formatMaxTwo(["1h30m10s", "45s"])).toEqual(["1h 30m", "45s"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('setLineChartData', () => {
|
||||
it('prepends min and appends max to data', () => {
|
||||
describe("setLineChartData", () => {
|
||||
it("prepends min and appends max to data", () => {
|
||||
const baseData = [
|
||||
{ x: 1, y: 10 }, { x: 2, y: 20 },
|
||||
{ x: 3, y: 30 }, { x: 4, y: 40 },
|
||||
{ x: 5, y: 50 }, { x: 6, y: 60 },
|
||||
{ x: 7, y: 70 }, { x: 8, y: 80 },
|
||||
{ x: 9, y: 90 }, { x: 10, y: 100 },
|
||||
{ x: 1, y: 10 },
|
||||
{ x: 2, y: 20 },
|
||||
{ x: 3, y: 30 },
|
||||
{ x: 4, y: 40 },
|
||||
{ x: 5, y: 50 },
|
||||
{ x: 6, y: 60 },
|
||||
{ x: 7, y: 70 },
|
||||
{ x: 8, y: 80 },
|
||||
{ x: 9, y: 90 },
|
||||
{ x: 10, y: 100 },
|
||||
];
|
||||
const result = setLineChartData(
|
||||
baseData, 'xMax', 'xMin', false, 200, 0
|
||||
);
|
||||
const result = setLineChartData(baseData, "xMax", "xMin", false, 200, 0);
|
||||
// Should have 12 elements (10 original + 2 boundary)
|
||||
expect(result).toHaveLength(12);
|
||||
expect(result[0].x).toBe('xMin');
|
||||
expect(result[11].x).toBe('xMax');
|
||||
expect(result[0].x).toBe("xMin");
|
||||
expect(result[11].x).toBe("xMax");
|
||||
});
|
||||
|
||||
it('clamps percent values between 0 and 1', () => {
|
||||
it("clamps percent values between 0 and 1", () => {
|
||||
const baseData = [
|
||||
{ x: 1, y: 0.1 }, { x: 2, y: 0.2 },
|
||||
{ x: 3, y: 0.3 }, { x: 4, y: 0.4 },
|
||||
{ x: 5, y: 0.5 }, { x: 6, y: 0.6 },
|
||||
{ x: 7, y: 0.7 }, { x: 8, y: 0.8 },
|
||||
{ x: 9, y: 0.9 }, { x: 10, y: 0.95 },
|
||||
{ x: 1, y: 0.1 },
|
||||
{ x: 2, y: 0.2 },
|
||||
{ x: 3, y: 0.3 },
|
||||
{ x: 4, y: 0.4 },
|
||||
{ x: 5, y: 0.5 },
|
||||
{ x: 6, y: 0.6 },
|
||||
{ x: 7, y: 0.7 },
|
||||
{ x: 8, y: 0.8 },
|
||||
{ x: 9, y: 0.9 },
|
||||
{ x: 10, y: 0.95 },
|
||||
];
|
||||
const result = setLineChartData(
|
||||
baseData, 'xMax', 'xMin', true, 1, 0
|
||||
);
|
||||
const result = setLineChartData(baseData, "xMax", "xMin", true, 1, 0);
|
||||
expect(result[0].y).toBeGreaterThanOrEqual(0);
|
||||
expect(result[0].y).toBeLessThanOrEqual(1);
|
||||
expect(result[11].y).toBeGreaterThanOrEqual(0);
|
||||
@@ -123,11 +128,9 @@ describe('setLineChartData', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('setBarChartData', () => {
|
||||
it('converts x values to formatted date strings', () => {
|
||||
const baseData = [
|
||||
{ x: '2023-01-15T12:00:00', y: 100 },
|
||||
];
|
||||
describe("setBarChartData", () => {
|
||||
it("converts x values to formatted date strings", () => {
|
||||
const baseData = [{ x: "2023-01-15T12:00:00", y: 100 }];
|
||||
const result = setBarChartData(baseData);
|
||||
expect(result[0].y).toBe(100);
|
||||
expect(result[0].x).toMatch(/2023\/1\/15/);
|
||||
|
||||
@@ -3,39 +3,38 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import shortScaleNumber from '@/module/shortScaleNumber.js';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import shortScaleNumber from "@/module/shortScaleNumber.js";
|
||||
|
||||
describe('shortScaleNumber', () => {
|
||||
it('returns small numbers without abbreviation', () => {
|
||||
expect(shortScaleNumber(1).trim()).toBe('1');
|
||||
expect(shortScaleNumber(999).trim()).toBe('999');
|
||||
describe("shortScaleNumber", () => {
|
||||
it("returns small numbers without abbreviation", () => {
|
||||
expect(shortScaleNumber(1).trim()).toBe("1");
|
||||
expect(shortScaleNumber(999).trim()).toBe("999");
|
||||
});
|
||||
|
||||
it('abbreviates thousands as k', () => {
|
||||
expect(shortScaleNumber(1000).trim()).toBe('1k');
|
||||
expect(shortScaleNumber(1500).trim()).toBe('1.5k');
|
||||
it("abbreviates thousands as k", () => {
|
||||
expect(shortScaleNumber(1000).trim()).toBe("1k");
|
||||
expect(shortScaleNumber(1500).trim()).toBe("1.5k");
|
||||
});
|
||||
|
||||
it('abbreviates millions as m', () => {
|
||||
expect(shortScaleNumber(1000000).trim()).toBe('1m');
|
||||
it("abbreviates millions as m", () => {
|
||||
expect(shortScaleNumber(1000000).trim()).toBe("1m");
|
||||
});
|
||||
|
||||
it('abbreviates billions as b', () => {
|
||||
expect(shortScaleNumber(1000000000).trim()).toBe('1b');
|
||||
it("abbreviates billions as b", () => {
|
||||
expect(shortScaleNumber(1000000000).trim()).toBe("1b");
|
||||
});
|
||||
|
||||
it('abbreviates trillions as t', () => {
|
||||
expect(shortScaleNumber(1000000000000).trim())
|
||||
.toBe('1t');
|
||||
it("abbreviates trillions as t", () => {
|
||||
expect(shortScaleNumber(1000000000000).trim()).toBe("1t");
|
||||
});
|
||||
|
||||
it('rounds up using Math.ceil', () => {
|
||||
it("rounds up using Math.ceil", () => {
|
||||
// 1234 -> 1.234k -> ceil(12.34)/10 = 1.3k
|
||||
expect(shortScaleNumber(1234).trim()).toBe('1.3k');
|
||||
expect(shortScaleNumber(1234).trim()).toBe("1.3k");
|
||||
});
|
||||
|
||||
it('handles zero', () => {
|
||||
expect(shortScaleNumber(0).trim()).toBe('0');
|
||||
it("handles zero", () => {
|
||||
expect(shortScaleNumber(0).trim()).toBe("0");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,55 +3,51 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
sortNumEngZhtw,
|
||||
sortNumEngZhtwForFilter,
|
||||
} from '@/module/sortNumEngZhtw.js';
|
||||
} from "@/module/sortNumEngZhtw.js";
|
||||
|
||||
describe('sortNumEngZhtw', () => {
|
||||
it('sorts numbers in ascending order', () => {
|
||||
expect(sortNumEngZhtw(['3', '1', '2']))
|
||||
.toEqual(['1', '2', '3']);
|
||||
describe("sortNumEngZhtw", () => {
|
||||
it("sorts numbers in ascending order", () => {
|
||||
expect(sortNumEngZhtw(["3", "1", "2"])).toEqual(["1", "2", "3"]);
|
||||
});
|
||||
|
||||
it('places numbers before strings', () => {
|
||||
expect(sortNumEngZhtw(['b', '1', 'a']))
|
||||
.toEqual(['1', 'a', 'b']);
|
||||
it("places numbers before strings", () => {
|
||||
expect(sortNumEngZhtw(["b", "1", "a"])).toEqual(["1", "a", "b"]);
|
||||
});
|
||||
|
||||
it('sorts English strings alphabetically', () => {
|
||||
expect(sortNumEngZhtw(['cherry', 'apple', 'banana']))
|
||||
.toEqual(['apple', 'banana', 'cherry']);
|
||||
it("sorts English strings alphabetically", () => {
|
||||
expect(sortNumEngZhtw(["cherry", "apple", "banana"])).toEqual([
|
||||
"apple",
|
||||
"banana",
|
||||
"cherry",
|
||||
]);
|
||||
});
|
||||
|
||||
it('sorts mixed numbers and strings', () => {
|
||||
const input = ['banana', '10', 'apple', '2'];
|
||||
it("sorts mixed numbers and strings", () => {
|
||||
const input = ["banana", "10", "apple", "2"];
|
||||
const result = sortNumEngZhtw(input);
|
||||
expect(result).toEqual(['2', '10', 'apple', 'banana']);
|
||||
expect(result).toEqual(["2", "10", "apple", "banana"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sortNumEngZhtwForFilter', () => {
|
||||
it('returns negative when a < b (numbers)', () => {
|
||||
expect(sortNumEngZhtwForFilter('1', '2'))
|
||||
.toBeLessThan(0);
|
||||
describe("sortNumEngZhtwForFilter", () => {
|
||||
it("returns negative when a < b (numbers)", () => {
|
||||
expect(sortNumEngZhtwForFilter("1", "2")).toBeLessThan(0);
|
||||
});
|
||||
|
||||
it('returns positive when a > b (numbers)', () => {
|
||||
expect(sortNumEngZhtwForFilter('10', '2'))
|
||||
.toBeGreaterThan(0);
|
||||
it("returns positive when a > b (numbers)", () => {
|
||||
expect(sortNumEngZhtwForFilter("10", "2")).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('places numbers before strings', () => {
|
||||
expect(sortNumEngZhtwForFilter('1', 'a'))
|
||||
.toBeLessThan(0);
|
||||
expect(sortNumEngZhtwForFilter('a', '1'))
|
||||
.toBeGreaterThan(0);
|
||||
it("places numbers before strings", () => {
|
||||
expect(sortNumEngZhtwForFilter("1", "a")).toBeLessThan(0);
|
||||
expect(sortNumEngZhtwForFilter("a", "1")).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('compares strings using locale', () => {
|
||||
expect(sortNumEngZhtwForFilter('a', 'b'))
|
||||
.toBeLessThan(0);
|
||||
it("compares strings using locale", () => {
|
||||
expect(sortNumEngZhtwForFilter("a", "b")).toBeLessThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
getTimeLabel,
|
||||
simpleTimeLabel,
|
||||
@@ -12,161 +12,163 @@ import {
|
||||
getYTicksByIndex,
|
||||
setTimeStringFormatBaseOnTimeDifference,
|
||||
mapTimestampToAxisTicksByFormat,
|
||||
} from '@/module/timeLabel.js';
|
||||
} from "@/module/timeLabel.js";
|
||||
|
||||
describe('getTimeLabel', () => {
|
||||
it('returns days for >= 86400 seconds', () => {
|
||||
expect(getTimeLabel(86400)).toBe('1 days');
|
||||
expect(getTimeLabel(172800)).toBe('2 days');
|
||||
describe("getTimeLabel", () => {
|
||||
it("returns days for >= 86400 seconds", () => {
|
||||
expect(getTimeLabel(86400)).toBe("1 days");
|
||||
expect(getTimeLabel(172800)).toBe("2 days");
|
||||
});
|
||||
|
||||
it('returns hours for >= 3600 seconds', () => {
|
||||
expect(getTimeLabel(3600)).toBe('1 hrs');
|
||||
expect(getTimeLabel(7200)).toBe('2 hrs');
|
||||
it("returns hours for >= 3600 seconds", () => {
|
||||
expect(getTimeLabel(3600)).toBe("1 hrs");
|
||||
expect(getTimeLabel(7200)).toBe("2 hrs");
|
||||
});
|
||||
|
||||
it('returns minutes for >= 60 seconds', () => {
|
||||
expect(getTimeLabel(60)).toBe('1 mins');
|
||||
expect(getTimeLabel(120)).toBe('2 mins');
|
||||
it("returns minutes for >= 60 seconds", () => {
|
||||
expect(getTimeLabel(60)).toBe("1 mins");
|
||||
expect(getTimeLabel(120)).toBe("2 mins");
|
||||
});
|
||||
|
||||
it('returns seconds for < 60', () => {
|
||||
expect(getTimeLabel(30)).toBe('30 sec');
|
||||
it("returns seconds for < 60", () => {
|
||||
expect(getTimeLabel(30)).toBe("30 sec");
|
||||
});
|
||||
|
||||
it('returns 0 sec for zero', () => {
|
||||
expect(getTimeLabel(0)).toBe('0 sec');
|
||||
it("returns 0 sec for zero", () => {
|
||||
expect(getTimeLabel(0)).toBe("0 sec");
|
||||
});
|
||||
|
||||
it('respects fixedNumber parameter', () => {
|
||||
expect(getTimeLabel(5400, 1)).toBe('1.5 hrs');
|
||||
it("respects fixedNumber parameter", () => {
|
||||
expect(getTimeLabel(5400, 1)).toBe("1.5 hrs");
|
||||
});
|
||||
});
|
||||
|
||||
describe('simpleTimeLabel', () => {
|
||||
it('returns days with d suffix', () => {
|
||||
expect(simpleTimeLabel(86400)).toBe('1d');
|
||||
describe("simpleTimeLabel", () => {
|
||||
it("returns days with d suffix", () => {
|
||||
expect(simpleTimeLabel(86400)).toBe("1d");
|
||||
});
|
||||
|
||||
it('returns hours with h suffix', () => {
|
||||
expect(simpleTimeLabel(3600)).toBe('1h');
|
||||
expect(simpleTimeLabel(7200)).toBe('2h');
|
||||
it("returns hours with h suffix", () => {
|
||||
expect(simpleTimeLabel(3600)).toBe("1h");
|
||||
expect(simpleTimeLabel(7200)).toBe("2h");
|
||||
});
|
||||
|
||||
it('returns minutes with m suffix', () => {
|
||||
expect(simpleTimeLabel(60)).toBe('1m');
|
||||
expect(simpleTimeLabel(120)).toBe('2m');
|
||||
it("returns minutes with m suffix", () => {
|
||||
expect(simpleTimeLabel(60)).toBe("1m");
|
||||
expect(simpleTimeLabel(120)).toBe("2m");
|
||||
});
|
||||
|
||||
it('returns seconds with s suffix for small values', () => {
|
||||
expect(simpleTimeLabel(30)).toBe('30s');
|
||||
it("returns seconds with s suffix for small values", () => {
|
||||
expect(simpleTimeLabel(30)).toBe("30s");
|
||||
});
|
||||
|
||||
it('returns 0s for zero', () => {
|
||||
expect(simpleTimeLabel(0)).toBe('0s');
|
||||
it("returns 0s for zero", () => {
|
||||
expect(simpleTimeLabel(0)).toBe("0s");
|
||||
});
|
||||
|
||||
it('correctly calculates hours for values between 1h and 1d', () => {
|
||||
it("correctly calculates hours for values between 1h and 1d", () => {
|
||||
// 5 hours = 18000 seconds -> should be "5h"
|
||||
expect(simpleTimeLabel(18000)).toBe('5h');
|
||||
expect(simpleTimeLabel(18000)).toBe("5h");
|
||||
});
|
||||
|
||||
it('correctly calculates minutes for values between 1m and 1h', () => {
|
||||
it("correctly calculates minutes for values between 1m and 1h", () => {
|
||||
// 30 minutes = 1800 seconds -> should be "30m"
|
||||
expect(simpleTimeLabel(1800)).toBe('30m');
|
||||
expect(simpleTimeLabel(1800)).toBe("30m");
|
||||
});
|
||||
});
|
||||
|
||||
describe('followTimeLabel', () => {
|
||||
it('uses day unit when max > 1 day', () => {
|
||||
describe("followTimeLabel", () => {
|
||||
it("uses day unit when max > 1 day", () => {
|
||||
// max = 100000 (> 86400), second = 86400 => 1d
|
||||
expect(followTimeLabel(86400, 100000)).toBe('1d');
|
||||
expect(followTimeLabel(86400, 100000)).toBe("1d");
|
||||
});
|
||||
|
||||
it('uses hour unit when max > 1 hour', () => {
|
||||
it("uses hour unit when max > 1 hour", () => {
|
||||
// max = 7200 (> 3600), second = 3600 => 1h
|
||||
expect(followTimeLabel(3600, 7200)).toBe('1h');
|
||||
expect(followTimeLabel(3600, 7200)).toBe("1h");
|
||||
});
|
||||
|
||||
it('uses minute unit when max > 1 minute', () => {
|
||||
it("uses minute unit when max > 1 minute", () => {
|
||||
// max = 120 (> 60), second = 60 => 1m
|
||||
expect(followTimeLabel(60, 120)).toBe('1m');
|
||||
expect(followTimeLabel(60, 120)).toBe("1m");
|
||||
});
|
||||
|
||||
it('uses second unit when max <= 60', () => {
|
||||
expect(followTimeLabel(30, 50)).toBe('30s');
|
||||
it("uses second unit when max <= 60", () => {
|
||||
expect(followTimeLabel(30, 50)).toBe("30s");
|
||||
});
|
||||
|
||||
it('returns 0 without decimals when value is 0', () => {
|
||||
expect(followTimeLabel(0, 7200, 2)).toBe('0h');
|
||||
it("returns 0 without decimals when value is 0", () => {
|
||||
expect(followTimeLabel(0, 7200, 2)).toBe("0h");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getStepSizeOfYTicks', () => {
|
||||
it('returns object with resultStepSize and unitToUse', () => {
|
||||
describe("getStepSizeOfYTicks", () => {
|
||||
it("returns object with resultStepSize and unitToUse", () => {
|
||||
const result = getStepSizeOfYTicks(7200, 5);
|
||||
expect(result).toHaveProperty('resultStepSize');
|
||||
expect(result).toHaveProperty('unitToUse');
|
||||
expect(result.unitToUse).toBe('h');
|
||||
expect(result).toHaveProperty("resultStepSize");
|
||||
expect(result).toHaveProperty("unitToUse");
|
||||
expect(result.unitToUse).toBe("h");
|
||||
});
|
||||
|
||||
it('uses day unit for large values', () => {
|
||||
it("uses day unit for large values", () => {
|
||||
const result = getStepSizeOfYTicks(200000, 5);
|
||||
expect(result.unitToUse).toBe('d');
|
||||
expect(result.unitToUse).toBe("d");
|
||||
});
|
||||
|
||||
it('uses second unit for small values', () => {
|
||||
it("uses second unit for small values", () => {
|
||||
const result = getStepSizeOfYTicks(30, 5);
|
||||
expect(result.unitToUse).toBe('s');
|
||||
expect(result.unitToUse).toBe("s");
|
||||
});
|
||||
});
|
||||
|
||||
describe('getYTicksByIndex', () => {
|
||||
it('formats tick label with unit', () => {
|
||||
expect(getYTicksByIndex(2, 3, 'h')).toBe('6h');
|
||||
describe("getYTicksByIndex", () => {
|
||||
it("formats tick label with unit", () => {
|
||||
expect(getYTicksByIndex(2, 3, "h")).toBe("6h");
|
||||
});
|
||||
|
||||
it('truncates to 1 decimal place', () => {
|
||||
expect(getYTicksByIndex(1.5, 1, 'h')).toBe('1.5h');
|
||||
it("truncates to 1 decimal place", () => {
|
||||
expect(getYTicksByIndex(1.5, 1, "h")).toBe("1.5h");
|
||||
});
|
||||
});
|
||||
|
||||
describe('setTimeStringFormatBaseOnTimeDifference', () => {
|
||||
it('returns seconds format for < 60s difference', () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 30))
|
||||
.toBe('HH:mm:ss');
|
||||
describe("setTimeStringFormatBaseOnTimeDifference", () => {
|
||||
it("returns seconds format for < 60s difference", () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 30)).toBe("HH:mm:ss");
|
||||
});
|
||||
|
||||
it('returns minute format for < 3600s difference', () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 1800))
|
||||
.toBe('MM/DD HH:mm');
|
||||
it("returns minute format for < 3600s difference", () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 1800)).toBe(
|
||||
"MM/DD HH:mm",
|
||||
);
|
||||
});
|
||||
|
||||
it('returns hour format for < 86400s difference', () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 43200))
|
||||
.toBe('MM/DD HH:mm');
|
||||
it("returns hour format for < 86400s difference", () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 43200)).toBe(
|
||||
"MM/DD HH:mm",
|
||||
);
|
||||
});
|
||||
|
||||
it('returns day format for < 30 days difference', () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 864000))
|
||||
.toBe('YYYY/MM/DD');
|
||||
it("returns day format for < 30 days difference", () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 864000)).toBe(
|
||||
"YYYY/MM/DD",
|
||||
);
|
||||
});
|
||||
|
||||
it('returns month format for >= 30 days difference', () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 5000000))
|
||||
.toBe('YYYY/MM/DD');
|
||||
it("returns month format for >= 30 days difference", () => {
|
||||
expect(setTimeStringFormatBaseOnTimeDifference(0, 5000000)).toBe(
|
||||
"YYYY/MM/DD",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapTimestampToAxisTicksByFormat', () => {
|
||||
it('formats timestamps with given format', () => {
|
||||
const ts = [new Date('2023-01-15').getTime()];
|
||||
const result = mapTimestampToAxisTicksByFormat(ts, 'YYYY/MM/DD');
|
||||
expect(result[0]).toBe('2023/01/15');
|
||||
describe("mapTimestampToAxisTicksByFormat", () => {
|
||||
it("formats timestamps with given format", () => {
|
||||
const ts = [new Date("2023-01-15").getTime()];
|
||||
const result = mapTimestampToAxisTicksByFormat(ts, "YYYY/MM/DD");
|
||||
expect(result[0]).toBe("2023/01/15");
|
||||
});
|
||||
|
||||
it('returns undefined for falsy input', () => {
|
||||
expect(mapTimestampToAxisTicksByFormat(null, 'YYYY'))
|
||||
.toBeUndefined();
|
||||
it("returns undefined for falsy input", () => {
|
||||
expect(mapTimestampToAxisTicksByFormat(null, "YYYY")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,17 +3,17 @@
|
||||
// Authors:
|
||||
// codex@openai.com (Codex), 2026/03/08
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createTooltipContent } from '@/module/tooltipContent.js';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { createTooltipContent } from "@/module/tooltipContent.js";
|
||||
|
||||
describe('createTooltipContent', () => {
|
||||
it('renders untrusted label as plain text', () => {
|
||||
const label = '<img src=x onerror=alert(1)>Node';
|
||||
describe("createTooltipContent", () => {
|
||||
it("renders untrusted label as plain text", () => {
|
||||
const label = "<img src=x onerror=alert(1)>Node";
|
||||
|
||||
const content = createTooltipContent(label);
|
||||
|
||||
expect(content.textContent).toBe(label);
|
||||
expect(content.innerHTML).toContain('<img');
|
||||
expect(content.querySelector('img')).toBeNull();
|
||||
expect(content.innerHTML).toContain("<img");
|
||||
expect(content.querySelector("img")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,108 +3,106 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import {
|
||||
getCookie,
|
||||
setCookie,
|
||||
setCookieWithoutExpiration,
|
||||
deleteCookie,
|
||||
} from '@/utils/cookieUtil.js';
|
||||
} from "@/utils/cookieUtil.js";
|
||||
|
||||
describe('cookieUtil', () => {
|
||||
describe("cookieUtil", () => {
|
||||
let cookieSetter;
|
||||
|
||||
beforeEach(() => {
|
||||
// Clear all cookies before each test
|
||||
document.cookie.split(';').forEach((c) => {
|
||||
const name = c.split('=')[0].trim();
|
||||
document.cookie.split(";").forEach((c) => {
|
||||
const name = c.split("=")[0].trim();
|
||||
if (name) {
|
||||
document.cookie =
|
||||
name + '=; Max-Age=-99999999; path=/';
|
||||
document.cookie = name + "=; Max-Age=-99999999; path=/";
|
||||
}
|
||||
});
|
||||
// Spy on document.cookie setter to capture the raw string
|
||||
// (jsdom silently drops Secure cookies on http://)
|
||||
cookieSetter = vi.spyOn(document, 'cookie', 'set');
|
||||
cookieSetter = vi.spyOn(document, "cookie", "set");
|
||||
});
|
||||
|
||||
describe('getCookie', () => {
|
||||
it('returns null when cookie does not exist', () => {
|
||||
expect(getCookie('nonexistent')).toBeNull();
|
||||
describe("getCookie", () => {
|
||||
it("returns null when cookie does not exist", () => {
|
||||
expect(getCookie("nonexistent")).toBeNull();
|
||||
});
|
||||
|
||||
it('returns value of an existing cookie', () => {
|
||||
document.cookie = 'testKey=testValue';
|
||||
expect(getCookie('testKey')).toBe('testValue');
|
||||
it("returns value of an existing cookie", () => {
|
||||
document.cookie = "testKey=testValue";
|
||||
expect(getCookie("testKey")).toBe("testValue");
|
||||
});
|
||||
|
||||
it('returns correct value when multiple cookies exist',
|
||||
() => {
|
||||
document.cookie = 'first=aaa';
|
||||
document.cookie = 'second=bbb';
|
||||
document.cookie = 'third=ccc';
|
||||
expect(getCookie('second')).toBe('bbb');
|
||||
});
|
||||
it("returns correct value when multiple cookies exist", () => {
|
||||
document.cookie = "first=aaa";
|
||||
document.cookie = "second=bbb";
|
||||
document.cookie = "third=ccc";
|
||||
expect(getCookie("second")).toBe("bbb");
|
||||
});
|
||||
|
||||
it('does not match partial cookie names', () => {
|
||||
document.cookie = 'testKey=value';
|
||||
expect(getCookie('test')).toBeNull();
|
||||
it("does not match partial cookie names", () => {
|
||||
document.cookie = "testKey=value";
|
||||
expect(getCookie("test")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setCookie', () => {
|
||||
it('sets cookie with Secure and SameSite=Lax flags', () => {
|
||||
setCookie('myKey', 'myValue');
|
||||
describe("setCookie", () => {
|
||||
it("sets cookie with Secure and SameSite=Lax flags", () => {
|
||||
setCookie("myKey", "myValue");
|
||||
|
||||
const written = cookieSetter.mock.calls.find(
|
||||
(c) => c[0].startsWith('myKey='),
|
||||
const written = cookieSetter.mock.calls.find((c) =>
|
||||
c[0].startsWith("myKey="),
|
||||
);
|
||||
expect(written).toBeDefined();
|
||||
const str = written[0];
|
||||
expect(str).toContain('myKey=myValue');
|
||||
expect(str).toContain('expires=');
|
||||
expect(str).toContain('path=/');
|
||||
expect(str).toContain('Secure');
|
||||
expect(str).toContain('SameSite=Lax');
|
||||
expect(str).toContain("myKey=myValue");
|
||||
expect(str).toContain("expires=");
|
||||
expect(str).toContain("path=/");
|
||||
expect(str).toContain("Secure");
|
||||
expect(str).toContain("SameSite=Lax");
|
||||
});
|
||||
});
|
||||
|
||||
describe('setCookieWithoutExpiration', () => {
|
||||
it('sets session cookie with Secure and SameSite=Lax flags', () => {
|
||||
setCookieWithoutExpiration('sessionKey', 'sessionVal');
|
||||
describe("setCookieWithoutExpiration", () => {
|
||||
it("sets session cookie with Secure and SameSite=Lax flags", () => {
|
||||
setCookieWithoutExpiration("sessionKey", "sessionVal");
|
||||
|
||||
const written = cookieSetter.mock.calls.find(
|
||||
(c) => c[0].startsWith('sessionKey='),
|
||||
const written = cookieSetter.mock.calls.find((c) =>
|
||||
c[0].startsWith("sessionKey="),
|
||||
);
|
||||
expect(written).toBeDefined();
|
||||
const str = written[0];
|
||||
expect(str).toContain('sessionKey=sessionVal');
|
||||
expect(str).toContain('Secure');
|
||||
expect(str).toContain('SameSite=Lax');
|
||||
expect(str).toContain("sessionKey=sessionVal");
|
||||
expect(str).toContain("Secure");
|
||||
expect(str).toContain("SameSite=Lax");
|
||||
});
|
||||
|
||||
it('sets cookie with path=/', () => {
|
||||
setCookieWithoutExpiration('pathKey', 'pathVal');
|
||||
it("sets cookie with path=/", () => {
|
||||
setCookieWithoutExpiration("pathKey", "pathVal");
|
||||
|
||||
const written = cookieSetter.mock.calls.find(
|
||||
(c) => c[0].startsWith('pathKey='),
|
||||
const written = cookieSetter.mock.calls.find((c) =>
|
||||
c[0].startsWith("pathKey="),
|
||||
);
|
||||
expect(written[0]).toContain('path=/');
|
||||
expect(written[0]).toContain("path=/");
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteCookie', () => {
|
||||
it('sets Max-Age=-99999999 with Secure and SameSite=Lax flags', () => {
|
||||
deleteCookie('toDelete');
|
||||
describe("deleteCookie", () => {
|
||||
it("sets Max-Age=-99999999 with Secure and SameSite=Lax flags", () => {
|
||||
deleteCookie("toDelete");
|
||||
|
||||
const written = cookieSetter.mock.calls.find(
|
||||
(c) => c[0].startsWith('toDelete='),
|
||||
const written = cookieSetter.mock.calls.find((c) =>
|
||||
c[0].startsWith("toDelete="),
|
||||
);
|
||||
expect(written).toBeDefined();
|
||||
const str = written[0];
|
||||
expect(str).toContain('Max-Age=-99999999');
|
||||
expect(str).toContain('Secure');
|
||||
expect(str).toContain('SameSite=Lax');
|
||||
expect(str).toContain("Max-Age=-99999999");
|
||||
expect(str).toContain("Secure");
|
||||
expect(str).toContain("SameSite=Lax");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,32 +3,33 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/06
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { escapeHtml } from '@/utils/escapeHtml.js';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { escapeHtml } from "@/utils/escapeHtml.js";
|
||||
|
||||
describe('escapeHtml', () => {
|
||||
it('escapes ampersand', () => {
|
||||
expect(escapeHtml('a&b')).toBe('a&b');
|
||||
describe("escapeHtml", () => {
|
||||
it("escapes ampersand", () => {
|
||||
expect(escapeHtml("a&b")).toBe("a&b");
|
||||
});
|
||||
|
||||
it('escapes angle brackets', () => {
|
||||
expect(escapeHtml('<script>')).toBe('<script>');
|
||||
it("escapes angle brackets", () => {
|
||||
expect(escapeHtml("<script>")).toBe("<script>");
|
||||
});
|
||||
|
||||
it('escapes double quotes', () => {
|
||||
expect(escapeHtml('"hello"')).toBe('"hello"');
|
||||
it("escapes double quotes", () => {
|
||||
expect(escapeHtml('"hello"')).toBe(""hello"");
|
||||
});
|
||||
|
||||
it('escapes single quotes', () => {
|
||||
it("escapes single quotes", () => {
|
||||
expect(escapeHtml("it's")).toBe("it's");
|
||||
});
|
||||
|
||||
it('escapes all special characters together', () => {
|
||||
expect(escapeHtml('<img src="x" onerror="alert(\'XSS\')">'))
|
||||
.toBe('<img src="x" onerror="alert('XSS')">');
|
||||
it("escapes all special characters together", () => {
|
||||
expect(escapeHtml('<img src="x" onerror="alert(\'XSS\')">')).toBe(
|
||||
"<img src="x" onerror="alert('XSS')">",
|
||||
);
|
||||
});
|
||||
|
||||
it('returns plain text unchanged', () => {
|
||||
expect(escapeHtml('hello world')).toBe('hello world');
|
||||
it("returns plain text unchanged", () => {
|
||||
expect(escapeHtml("hello world")).toBe("hello world");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,57 +3,47 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/05
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
mapPageNameToCapitalUnifiedName,
|
||||
} from '@/utils/pageUtils.js';
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { mapPageNameToCapitalUnifiedName } from "@/utils/pageUtils.js";
|
||||
|
||||
describe('pageUtils', () => {
|
||||
describe('mapPageNameToCapitalUnifiedName', () => {
|
||||
it('converts CheckMap to MAP', () => {
|
||||
expect(mapPageNameToCapitalUnifiedName('CheckMap'))
|
||||
.toBe('MAP');
|
||||
describe("pageUtils", () => {
|
||||
describe("mapPageNameToCapitalUnifiedName", () => {
|
||||
it("converts CheckMap to MAP", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName("CheckMap")).toBe("MAP");
|
||||
});
|
||||
|
||||
it('converts CheckConformance to CONFORMANCE', () => {
|
||||
expect(
|
||||
mapPageNameToCapitalUnifiedName('CheckConformance')
|
||||
).toBe('CONFORMANCE');
|
||||
it("converts CheckConformance to CONFORMANCE", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName("CheckConformance")).toBe(
|
||||
"CONFORMANCE",
|
||||
);
|
||||
});
|
||||
|
||||
it('converts CheckPerformance to PERFORMANCE', () => {
|
||||
expect(
|
||||
mapPageNameToCapitalUnifiedName('CheckPerformance')
|
||||
).toBe('PERFORMANCE');
|
||||
it("converts CheckPerformance to PERFORMANCE", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName("CheckPerformance")).toBe(
|
||||
"PERFORMANCE",
|
||||
);
|
||||
});
|
||||
|
||||
it('converts CompareDashboard to DASHBOARD', () => {
|
||||
expect(
|
||||
mapPageNameToCapitalUnifiedName('CompareDashboard')
|
||||
).toBe('DASHBOARD');
|
||||
it("converts CompareDashboard to DASHBOARD", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName("CompareDashboard")).toBe(
|
||||
"DASHBOARD",
|
||||
);
|
||||
});
|
||||
|
||||
it('converts other names to uppercase', () => {
|
||||
expect(mapPageNameToCapitalUnifiedName('files'))
|
||||
.toBe('FILES');
|
||||
expect(mapPageNameToCapitalUnifiedName('Map'))
|
||||
.toBe('MAP');
|
||||
it("converts other names to uppercase", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName("files")).toBe("FILES");
|
||||
expect(mapPageNameToCapitalUnifiedName("Map")).toBe("MAP");
|
||||
});
|
||||
|
||||
it('handles case-insensitive input', () => {
|
||||
expect(mapPageNameToCapitalUnifiedName('checkmap'))
|
||||
.toBe('MAP');
|
||||
expect(mapPageNameToCapitalUnifiedName('CHECKMAP'))
|
||||
.toBe('MAP');
|
||||
it("handles case-insensitive input", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName("checkmap")).toBe("MAP");
|
||||
expect(mapPageNameToCapitalUnifiedName("CHECKMAP")).toBe("MAP");
|
||||
});
|
||||
|
||||
it('returns undefined for falsy input', () => {
|
||||
expect(mapPageNameToCapitalUnifiedName(undefined))
|
||||
.toBeUndefined();
|
||||
expect(mapPageNameToCapitalUnifiedName(null))
|
||||
.toBeUndefined();
|
||||
expect(mapPageNameToCapitalUnifiedName(''))
|
||||
.toBeUndefined();
|
||||
it("returns undefined for falsy input", () => {
|
||||
expect(mapPageNameToCapitalUnifiedName(undefined)).toBeUndefined();
|
||||
expect(mapPageNameToCapitalUnifiedName(null)).toBeUndefined();
|
||||
expect(mapPageNameToCapitalUnifiedName("")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,41 +3,41 @@
|
||||
// Authors:
|
||||
// imacat.yang@dsp.im (imacat), 2026/03/06
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { setActivePinia, createPinia } from 'pinia';
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { setActivePinia, createPinia } from "pinia";
|
||||
|
||||
// Mock all heavy imports that MainContainer.vue pulls in
|
||||
vi.mock('@/stores/loading', () => ({
|
||||
vi.mock("@/stores/loading", () => ({
|
||||
useLoadingStore: () => ({ isLoading: false }),
|
||||
}));
|
||||
vi.mock('@/stores/allMapData', () => ({
|
||||
vi.mock("@/stores/allMapData", () => ({
|
||||
useAllMapDataStore: () => ({}),
|
||||
}));
|
||||
vi.mock('@/stores/conformance', () => ({
|
||||
vi.mock("@/stores/conformance", () => ({
|
||||
useConformanceStore: () => ({}),
|
||||
}));
|
||||
vi.mock('@/stores/pageAdmin', () => ({
|
||||
vi.mock("@/stores/pageAdmin", () => ({
|
||||
usePageAdminStore: () => ({}),
|
||||
}));
|
||||
vi.mock('@/module/alertModal.js', () => ({
|
||||
vi.mock("@/module/alertModal.js", () => ({
|
||||
leaveFilter: vi.fn(),
|
||||
leaveConformance: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/module/apiError.js', () => ({
|
||||
vi.mock("@/module/apiError.js", () => ({
|
||||
default: vi.fn(),
|
||||
}));
|
||||
vi.mock('@/router/index.ts', () => ({
|
||||
default: { push: vi.fn(), currentRoute: { value: { path: '/' } } },
|
||||
vi.mock("@/router/index.ts", () => ({
|
||||
default: { push: vi.fn(), currentRoute: { value: { path: "/" } } },
|
||||
}));
|
||||
vi.mock('@/module/cytoscapeMap.js', () => ({}));
|
||||
vi.mock("@/module/cytoscapeMap.js", () => ({}));
|
||||
|
||||
import { useLoginStore } from '@/stores/login';
|
||||
import * as cookieUtil from '@/utils/cookieUtil.js';
|
||||
import { useLoginStore } from "@/stores/login";
|
||||
import * as cookieUtil from "@/utils/cookieUtil.js";
|
||||
|
||||
// Import the component definition to access beforeRouteEnter
|
||||
import MainContainer from '@/views/MainContainer.vue';
|
||||
import MainContainer from "@/views/MainContainer.vue";
|
||||
|
||||
describe('MainContainer beforeRouteEnter', () => {
|
||||
describe("MainContainer beforeRouteEnter", () => {
|
||||
let loginStore;
|
||||
let next;
|
||||
|
||||
@@ -48,10 +48,10 @@ describe('MainContainer beforeRouteEnter', () => {
|
||||
next = vi.fn();
|
||||
vi.clearAllMocks();
|
||||
// Clear cookies
|
||||
document.cookie.split(';').forEach((c) => {
|
||||
const name = c.split('=')[0].trim();
|
||||
document.cookie.split(";").forEach((c) => {
|
||||
const name = c.split("=")[0].trim();
|
||||
if (name) {
|
||||
document.cookie = name + '=; Max-Age=-99999999; path=/';
|
||||
document.cookie = name + "=; Max-Age=-99999999; path=/";
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -61,10 +61,10 @@ describe('MainContainer beforeRouteEnter', () => {
|
||||
return guard({}, {}, next);
|
||||
};
|
||||
|
||||
it('calls next() after successful refreshToken', async () => {
|
||||
it("calls next() after successful refreshToken", async () => {
|
||||
// Not logged in, but has refresh token
|
||||
document.cookie = 'luciaRefreshToken=some-token';
|
||||
vi.spyOn(loginStore, 'refreshToken').mockResolvedValue();
|
||||
document.cookie = "luciaRefreshToken=some-token";
|
||||
vi.spyOn(loginStore, "refreshToken").mockResolvedValue();
|
||||
|
||||
await callGuard();
|
||||
|
||||
@@ -72,34 +72,38 @@ describe('MainContainer beforeRouteEnter', () => {
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to login when refreshToken fails', async () => {
|
||||
it("redirects to login when refreshToken fails", async () => {
|
||||
// Not logged in, has refresh token, but refresh fails
|
||||
document.cookie = 'luciaRefreshToken=some-token';
|
||||
vi.spyOn(loginStore, 'refreshToken').mockRejectedValue(new Error('401'));
|
||||
document.cookie = "luciaRefreshToken=some-token";
|
||||
vi.spyOn(loginStore, "refreshToken").mockRejectedValue(new Error("401"));
|
||||
|
||||
await callGuard();
|
||||
|
||||
expect(next).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ path: '/login' }),
|
||||
expect.objectContaining({ path: "/login" }),
|
||||
);
|
||||
});
|
||||
|
||||
it('calls next() when already logged in', async () => {
|
||||
document.cookie = 'isLuciaLoggedIn=true';
|
||||
it("calls next() when already logged in", async () => {
|
||||
document.cookie = "isLuciaLoggedIn=true";
|
||||
|
||||
await callGuard();
|
||||
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stores a relative return-to path when redirecting to login', async () => {
|
||||
window.history.replaceState({}, '', '/discover/log/1/map?view=summary#node-2');
|
||||
it("stores a relative return-to path when redirecting to login", async () => {
|
||||
window.history.replaceState(
|
||||
{},
|
||||
"",
|
||||
"/discover/log/1/map?view=summary#node-2",
|
||||
);
|
||||
|
||||
await callGuard();
|
||||
|
||||
const redirectArg = next.mock.calls[0][0];
|
||||
const returnTo = redirectArg.query['return-to'];
|
||||
const returnTo = redirectArg.query["return-to"];
|
||||
|
||||
expect(atob(returnTo)).toBe('/discover/log/1/map?view=summary#node-2');
|
||||
expect(atob(returnTo)).toBe("/discover/log/1/map?view=summary#node-2");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user