/** * 切公司/快速改筛选时,旧响应不得覆盖新结果(CR-27)。 * * 跑真组件 + 真 pinia store,API 用可控 deferred 顶掉: * 先让新请求落地,再让旧请求后返回,断言页面仍显示新结果。 * * 跑法:`npx vitest run tests/mount/stale-response-drop.mount.test.ts` */ import { beforeEach, describe, expect, it, vi } from 'vitest' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { createPinia, setActivePinia, type Pinia } from 'pinia' import KeywordUsagePage from '@/pages/tasks/KeywordUsagePage.vue' import BrandGatingPanel from '@/pages/tasks/BrandGatingPanel.vue' import { useAdminSessionStore } from '@/stores/admin-session' import { useCompanyTabStore } from '@/stores/company-tab' const keywordApi = vi.hoisted(() => ({ fetchKeywordUsage: vi.fn(), fetchKeywordUsageDeletes: vi.fn(), fetchKeywordUsageOverview: vi.fn(), })) const gatingApi = vi.hoisted(() => ({ fetchBrandGatingPage: vi.fn(), fetchBrandGatingStats: vi.fn(), deleteBrandGating: vi.fn(), importBrandGatingText: vi.fn(), submitBrandGating: vi.fn(), updateBrandGatingStatus: vi.fn(), })) vi.mock('@/pages/tasks/keyword-usage-api.ts', () => keywordApi) vi.mock('@/pages/tasks/brand-gating-api.ts', () => gatingApi) interface Deferred { promise: Promise resolve: (value: T) => void } function deferred(): Deferred { let resolve!: (value: T) => void const promise = new Promise((done) => { resolve = done }) return { promise, resolve } } const loadingDirective = { mounted() {}, updated() {} } function mountPage(component: Parameters[0], pinia: Pinia): VueWrapper { return mount(component, { global: { plugins: [pinia], directives: { loading: loadingDirective }, }, }) } function usagePage(keyword: string) { return { total: 1, rows: [{ userName: 'alice', country: '英国', keyword, scene: '复制关键词', time: '2026-10-25 10:00:00', }], counts: { copy: 1, copyExisting: 1, copyDeleted: 0, add: 0 }, } } function gatingPage(brand: string) { return { total: 1, rows: [{ id: 1, brand, asin: '', country: '英国', gatingType: '品牌gating', status: 1, source: 'MANUAL', shopName: '', remark: '', createdAt: '2026-10-25 10:00:00', updatedAt: '', disabledAt: '', }], } } describe('CR-27:切换期间晚到的响应必须丢弃', () => { let pinia: Pinia beforeEach(() => { vi.clearAllMocks() pinia = createPinia() setActivePinia(pinia) useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' } // 只有超管才带 company_id;company tab 的 activeId 直接改,不依赖公司目录接口 useCompanyTabStore().setActiveId(1) keywordApi.fetchKeywordUsageOverview.mockResolvedValue({ stats: { used: 0, exist: 0, deletedKw: 0, added: 0, totalUse: 0, deletes: 0 }, users: [], countries: [], }) keywordApi.fetchKeywordUsageDeletes.mockResolvedValue({ total: 0, rows: [], counts: { copy: 0, copyExisting: 0, copyDeleted: 0, add: 0 }, }) gatingApi.fetchBrandGatingStats.mockResolvedValue({ total: 0, active: 0, disabled: 0, brands: 0, byType: [], byCountry: [], bySource: [], }) }) it('关键词使用记录:切公司后旧公司响应后到,页面仍显示新公司数据', async () => { const calls: Array<{ companyId?: number | null pageSize?: number deferred: Deferred> }> = [] keywordApi.fetchKeywordUsage.mockImplementation((params: { companyId?: number | null; pageSize?: number }) => { const pending = deferred>() calls.push({ companyId: params.companyId, pageSize: params.pageSize, deferred: pending }) return pending.promise }) const wrapper = mountPage(KeywordUsagePage, pinia) await flushPromises() expect(calls).toHaveLength(1) expect(calls[0].companyId).toBe(1) expect(calls[0].pageSize).toBe(10) useCompanyTabStore().setActiveId(2) await flushPromises() expect(calls).toHaveLength(2) expect(calls[1].companyId).toBe(2) calls[1].deferred.resolve(usagePage('beta-keyword')) await flushPromises() expect(wrapper.text()).toContain('beta-keyword') // 旧公司的响应晚到:序号闸必须把它丢掉 calls[0].deferred.resolve(usagePage('alpha-keyword')) await flushPromises() expect(wrapper.text()).toContain('beta-keyword') expect(wrapper.text()).not.toContain('alpha-keyword') }) it('品牌 Gating:快速改筛选时旧筛选响应后到,列表仍显示新筛选结果', async () => { const calls: Array<{ keyword: string deferred: Deferred> }> = [] gatingApi.fetchBrandGatingPage.mockImplementation((filter: { keyword: string }) => { const pending = deferred>() calls.push({ keyword: filter.keyword, deferred: pending }) return pending.promise }) const wrapper = mountPage(BrandGatingPanel, pinia) await flushPromises() expect(calls).toHaveLength(1) calls[0].deferred.resolve(gatingPage('initial-brand')) await flushPromises() expect(wrapper.text()).toContain('initial-brand') const input = wrapper.get('input[placeholder="搜索品牌 / ASIN"]') const queryButton = wrapper.findAll('button').find((button) => button.text() === '查询') expect(queryButton, '页面里应有「查询」按钮').toBeDefined() await input.setValue('old') await queryButton!.trigger('click') await flushPromises() expect(calls).toHaveLength(2) expect(calls[1].keyword).toBe('old') await input.setValue('new') await queryButton!.trigger('click') await flushPromises() expect(calls).toHaveLength(3) expect(calls[2].keyword).toBe('new') calls[2].deferred.resolve(gatingPage('new-brand')) await flushPromises() expect(wrapper.text()).toContain('new-brand') calls[1].deferred.resolve(gatingPage('old-brand')) await flushPromises() expect(wrapper.text()).toContain('new-brand') expect(wrapper.text()).not.toContain('old-brand') }) })