feat(cache): implement Redis caching for search & analytics hot paths

- Add TTL-specific cache durations: district stats (5min), market report (15min), heatmap (5min)
- Add Redis caching to GeoSearch handler with 60s TTL
- Add cache invalidation on listing.approved, listing.updated, listing.deactivated, listing.sold events
- Invalidate search, geo_search, and all analytics cache prefixes on listing state changes
- Update tests for new CacheService dependency in event handler and geo-search handler

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 22:51:16 +07:00
parent 03231271ca
commit ccb82fddf8
18 changed files with 1885 additions and 19 deletions

View File

@@ -0,0 +1,145 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useAuthStore } from '@/lib/auth-store';
// Mock next/navigation
const mockPush = vi.fn();
const mockSearchParams = new URLSearchParams();
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
useSearchParams: () => mockSearchParams,
}));
// Mock next/link
vi.mock('next/link', () => ({
default: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
<a href={href} {...props}>{children}</a>
),
}));
// Mock auth store
vi.mock('@/lib/auth-store', () => {
const store = {
login: vi.fn(),
isLoading: false,
error: null,
clearError: vi.fn(),
};
return {
useAuthStore: vi.fn((selector) => {
if (typeof selector === 'function') return selector(store);
return store;
}),
};
});
import LoginPage from '../login/page';
const mockedUseAuthStore = vi.mocked(useAuthStore);
describe('LoginPage', () => {
let mockStore: {
login: ReturnType<typeof vi.fn>;
isLoading: boolean;
error: string | null;
clearError: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.clearAllMocks();
mockStore = {
login: vi.fn(),
isLoading: false,
error: null,
clearError: vi.fn(),
};
mockedUseAuthStore.mockImplementation((selector) => {
if (typeof selector === 'function') return (selector as (s: typeof mockStore) => unknown)(mockStore);
return mockStore as ReturnType<typeof useAuthStore>;
});
});
it('renders login form with phone and password fields', () => {
render(<LoginPage />);
expect(screen.getByRole('heading', { name: 'Đăng nhập' })).toBeInTheDocument();
expect(screen.getByLabelText('Số điện thoại')).toBeInTheDocument();
expect(screen.getByLabelText('Mật khẩu')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /đăng nhập/i })).toBeInTheDocument();
});
it('renders OAuth buttons', () => {
render(<LoginPage />);
expect(screen.getByRole('button', { name: /google/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /zalo/i })).toBeInTheDocument();
});
it('renders register link', () => {
render(<LoginPage />);
const registerLink = screen.getByRole('link', { name: /đăng ký/i });
expect(registerLink).toHaveAttribute('href', '/register');
});
it('submits form with valid data', async () => {
mockStore.login.mockResolvedValue(undefined);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
await waitFor(() => {
expect(mockStore.login).toHaveBeenCalledWith({
phone: '0912345678',
password: 'password123',
});
});
});
it('shows validation errors for empty fields', async () => {
render(<LoginPage />);
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
await waitFor(() => {
const alerts = screen.getAllByRole('alert');
expect(alerts.length).toBeGreaterThan(0);
});
});
it('toggles password visibility', async () => {
render(<LoginPage />);
const passwordInput = screen.getByLabelText('Mật khẩu');
expect(passwordInput).toHaveAttribute('type', 'password');
await userEvent.click(screen.getByText('Hiện'));
expect(passwordInput).toHaveAttribute('type', 'text');
await userEvent.click(screen.getByText('Ẩn'));
expect(passwordInput).toHaveAttribute('type', 'password');
});
it('displays store error message', () => {
mockStore.error = 'Sai mật khẩu';
render(<LoginPage />);
expect(screen.getByText('Sai mật khẩu')).toBeInTheDocument();
});
it('navigates to home after successful login', async () => {
mockStore.login.mockResolvedValue(undefined);
render(<LoginPage />);
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
await userEvent.click(screen.getByRole('button', { name: /đăng nhập/i }));
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith('/');
});
});
});

View File

@@ -0,0 +1,145 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useAuthStore } from '@/lib/auth-store';
const mockPush = vi.fn();
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}));
vi.mock('next/link', () => ({
default: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
<a href={href} {...props}>{children}</a>
),
}));
vi.mock('@/lib/auth-store', () => {
const store = {
register: vi.fn(),
isLoading: false,
error: null,
clearError: vi.fn(),
};
return {
useAuthStore: vi.fn((selector) => {
if (typeof selector === 'function') return selector(store);
return store;
}),
};
});
import RegisterPage from '../register/page';
const mockedUseAuthStore = vi.mocked(useAuthStore);
describe('RegisterPage', () => {
let mockStore: {
register: ReturnType<typeof vi.fn>;
isLoading: boolean;
error: string | null;
clearError: ReturnType<typeof vi.fn>;
};
beforeEach(() => {
vi.clearAllMocks();
mockStore = {
register: vi.fn(),
isLoading: false,
error: null,
clearError: vi.fn(),
};
mockedUseAuthStore.mockImplementation((selector) => {
if (typeof selector === 'function') return (selector as (s: typeof mockStore) => unknown)(mockStore);
return mockStore as ReturnType<typeof useAuthStore>;
});
});
it('renders register form with all fields', () => {
render(<RegisterPage />);
expect(screen.getByText('Tạo tài khoản')).toBeInTheDocument();
expect(screen.getByLabelText('Họ và tên')).toBeInTheDocument();
expect(screen.getByLabelText('Số điện thoại')).toBeInTheDocument();
expect(screen.getByLabelText(/email/i)).toBeInTheDocument();
expect(screen.getByLabelText('Mật khẩu')).toBeInTheDocument();
expect(screen.getByLabelText('Xác nhận mật khẩu')).toBeInTheDocument();
});
it('renders login link', () => {
render(<RegisterPage />);
const loginLink = screen.getByRole('link', { name: /đăng nhập/i });
expect(loginLink).toHaveAttribute('href', '/login');
});
it('submits form with valid data', async () => {
mockStore.register.mockResolvedValue(undefined);
render(<RegisterPage />);
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'password123');
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
await waitFor(() => {
expect(mockStore.register).toHaveBeenCalledWith({
phone: '0912345678',
password: 'password123',
fullName: 'Nguyen Van A',
email: undefined,
});
});
});
it('shows validation error for short password', async () => {
render(<RegisterPage />);
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'short');
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'short');
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
await waitFor(() => {
const alerts = screen.getAllByRole('alert');
expect(alerts.length).toBeGreaterThan(0);
});
});
it('shows error when passwords do not match', async () => {
render(<RegisterPage />);
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'differentpw');
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
await waitFor(() => {
const alerts = screen.getAllByRole('alert');
expect(alerts.length).toBeGreaterThan(0);
});
});
it('displays store error message', () => {
mockStore.error = 'Số điện thoại đã tồn tại';
render(<RegisterPage />);
expect(screen.getByText('Số điện thoại đã tồn tại')).toBeInTheDocument();
});
it('navigates to home after successful registration', async () => {
mockStore.register.mockResolvedValue(undefined);
render(<RegisterPage />);
await userEvent.type(screen.getByLabelText('Họ và tên'), 'Nguyen Van A');
await userEvent.type(screen.getByLabelText('Số điện thoại'), '0912345678');
await userEvent.type(screen.getByLabelText('Mật khẩu'), 'password123');
await userEvent.type(screen.getByLabelText('Xác nhận mật khẩu'), 'password123');
await userEvent.click(screen.getByRole('button', { name: /đăng ký/i }));
await waitFor(() => {
expect(mockPush).toHaveBeenCalledWith('/');
});
});
});

View File

@@ -0,0 +1,110 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mockPush = vi.fn();
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}));
vi.mock('@/lib/listings-api', () => ({
listingsApi: {
create: vi.fn(),
uploadMedia: vi.fn(),
},
}));
vi.mock('@/components/listings/image-upload', () => ({
ImageUpload: ({ onChange }: { onChange: (imgs: unknown[]) => void }) => (
<div data-testid="image-upload">
<button type="button" onClick={() => onChange([])}>Upload Mock</button>
</div>
),
}));
import { listingsApi } from '@/lib/listings-api';
import CreateListingPage from '../new/page';
const mockedListingsApi = vi.mocked(listingsApi);
describe('CreateListingPage', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders the page title and step indicators', () => {
render(<CreateListingPage />);
expect(screen.getByText('Đăng tin mới')).toBeInTheDocument();
expect(screen.getByText('Thông tin')).toBeInTheDocument();
expect(screen.getByText('Vị trí')).toBeInTheDocument();
expect(screen.getByText('Chi tiết')).toBeInTheDocument();
expect(screen.getByText('Giá cả')).toBeInTheDocument();
expect(screen.getByText('Hình ảnh')).toBeInTheDocument();
});
it('renders step 1 (basic info) initially', () => {
render(<CreateListingPage />);
expect(screen.getByText('Thông tin cơ bản')).toBeInTheDocument();
expect(screen.getByLabelText(/loại giao dịch/i)).toBeInTheDocument();
expect(screen.getByLabelText(/loại bất động sản/i)).toBeInTheDocument();
expect(screen.getByLabelText(/tiêu đề/i)).toBeInTheDocument();
expect(screen.getByLabelText(/mô tả/i)).toBeInTheDocument();
});
it('has back button disabled on first step', () => {
render(<CreateListingPage />);
expect(screen.getByRole('button', { name: /quay lại/i })).toBeDisabled();
});
it('navigates to step 2 when basic info is filled and next is clicked', async () => {
render(<CreateListingPage />);
// Fill step 1
await userEvent.selectOptions(screen.getByLabelText(/loại giao dịch/i), 'SALE');
await userEvent.selectOptions(screen.getByLabelText(/loại bất động sản/i), 'APARTMENT');
await userEvent.type(screen.getByLabelText(/tiêu đề/i), 'Bán căn hộ 2PN tại Quận 7');
await userEvent.type(screen.getByLabelText(/mô tả/i), 'Căn hộ view sông tuyệt đẹp, nội thất cao cấp');
await userEvent.click(screen.getByRole('button', { name: /tiếp theo/i }));
await waitFor(() => {
expect(screen.getByLabelText(/địa chỉ/i)).toBeInTheDocument();
});
});
it('shows validation errors when required fields are empty on step 1', async () => {
render(<CreateListingPage />);
await userEvent.click(screen.getByRole('button', { name: /tiếp theo/i }));
// Step should not advance - still showing basic info
await waitFor(() => {
expect(screen.getByText('Thông tin cơ bản')).toBeInTheDocument();
});
});
it('navigates back to previous step', async () => {
render(<CreateListingPage />);
// Fill step 1 and go to step 2
await userEvent.selectOptions(screen.getByLabelText(/loại giao dịch/i), 'SALE');
await userEvent.selectOptions(screen.getByLabelText(/loại bất động sản/i), 'APARTMENT');
await userEvent.type(screen.getByLabelText(/tiêu đề/i), 'Test listing title here');
await userEvent.type(screen.getByLabelText(/mô tả/i), 'A detailed description of the property for sale');
await userEvent.click(screen.getByRole('button', { name: /tiếp theo/i }));
await waitFor(() => {
expect(screen.getByLabelText(/địa chỉ/i)).toBeInTheDocument();
});
// Go back
await userEvent.click(screen.getByRole('button', { name: /quay lại/i }));
await waitFor(() => {
expect(screen.getByText('Thông tin cơ bản')).toBeInTheDocument();
});
});
});

View File

@@ -0,0 +1,140 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const mockPush = vi.fn();
const mockReplace = vi.fn();
const mockSearchParams = new URLSearchParams();
vi.mock('next/navigation', () => ({
useRouter: () => ({ push: mockPush, replace: mockReplace }),
useSearchParams: () => mockSearchParams,
}));
vi.mock('next/link', () => ({
default: ({ children, href, ...props }: { children: React.ReactNode; href: string; [key: string]: unknown }) => (
<a href={href} {...props}>{children}</a>
),
}));
vi.mock('next/image', () => ({
default: (props: Record<string, unknown>) => <img {...props} />,
}));
// Mock dynamic import for map component
vi.mock('next/dynamic', () => ({
default: () => {
const MockMap = () => <div data-testid="map-placeholder">Map</div>;
MockMap.displayName = 'MockMap';
return MockMap;
},
}));
const mockListings = {
data: [
{
id: '1',
status: 'ACTIVE',
transactionType: 'SALE',
priceVND: '5000000000',
pricePerM2: null,
rentPriceMonthly: null,
commissionPct: null,
viewCount: 10,
saveCount: 2,
inquiryCount: 1,
publishedAt: '2024-01-01',
createdAt: '2024-01-01',
property: {
id: 'p1',
propertyType: 'APARTMENT',
title: 'Căn hộ Quận 7',
description: 'Căn hộ view sông',
address: '123 Nguyễn Hữu Thọ',
ward: 'Phường Tân Hưng',
district: 'Quận 7',
city: 'Hồ Chí Minh',
areaM2: 75,
bedrooms: 2,
bathrooms: 2,
floors: null,
direction: null,
yearBuilt: null,
legalStatus: null,
amenities: null,
projectName: null,
media: [],
},
seller: { id: 's1', fullName: 'Nguyen Van A', phone: '0912345678' },
agent: null,
},
],
total: 1,
page: 1,
limit: 12,
totalPages: 1,
};
vi.mock('@/lib/listings-api', () => ({
listingsApi: {
search: vi.fn(),
},
}));
import { listingsApi } from '@/lib/listings-api';
import SearchPage from '../page';
const mockedListingsApi = vi.mocked(listingsApi);
describe('SearchPage', () => {
beforeEach(() => {
vi.clearAllMocks();
mockedListingsApi.search.mockResolvedValue(mockListings as never);
});
it('renders the search page title', async () => {
render(<SearchPage />);
await waitFor(() => {
expect(screen.getByText('Tìm kiếm bất động sản')).toBeInTheDocument();
});
});
it('renders view mode toggle buttons', async () => {
render(<SearchPage />);
await waitFor(() => {
expect(screen.getByRole('button', { name: /danh sách/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /bản đồ/i })).toBeInTheDocument();
});
});
it('calls listings API on mount', async () => {
render(<SearchPage />);
await waitFor(() => {
expect(mockedListingsApi.search).toHaveBeenCalled();
});
});
it('displays listing results after loading', async () => {
render(<SearchPage />);
await waitFor(() => {
expect(screen.getByText(/căn hộ quận 7/i)).toBeInTheDocument();
});
});
it('switches to map view when map button is clicked', async () => {
render(<SearchPage />);
await waitFor(() => {
expect(screen.getByRole('button', { name: /bản đồ/i })).toBeInTheDocument();
});
await userEvent.click(screen.getByRole('button', { name: /bản đồ/i }));
await waitFor(() => {
expect(screen.getByTestId('map-placeholder')).toBeInTheDocument();
});
});
});