fix(blog): sort articles by raw publication timestamps
This commit is contained in:
1 parent
f4678c48ca
commit
3805057923
2 files changed
+73
-4
No files matched your search
@@ -105,10 +105,10 @@ export default function BlogPage({
|
||||
if (sortBy === "most_viewed") {
|
||||
return (b.viewCount ?? 0) - (a.viewCount ?? 0);
|
||||
}
|
||||
if (sortBy === "oldest") {
|
||||
return new Date(a.date).getTime() - new Date(b.date).getTime();
|
||||
}
|
||||
return new Date(b.date).getTime() - new Date(a.date).getTime();
|
||||
// `date` is a localized Persian display value, not a parseable timestamp.
|
||||
const aPublished = Date.parse(publicationDate(a) || '') || 0;
|
||||
const bPublished = Date.parse(publicationDate(b) || '') || 0;
|
||||
return sortBy === "oldest" ? aPublished - bPublished : bPublished - aPublished;
|
||||
});
|
||||
}, [blogs, selectedCategory, searchQuery, selectedTag, sortBy]);
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import React from 'react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
|
||||
import BlogPage, { type BlogPostItem } from '../BlogPage';
|
||||
|
||||
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: vi.fn(), replace: vi.fn() }) }));
|
||||
vi.mock('../../lib/services/productService', () => ({ productService: { getProducts: vi.fn().mockResolvedValue({ data: [] }) } }));
|
||||
vi.mock('next/image', () => ({ default: ({ fill, priority, unoptimized, ...props }: any) => <img {...props} /> }));
|
||||
vi.mock('motion/react', async () => {
|
||||
const React = await import('react');
|
||||
const cache: Record<string, React.ComponentType<any>> = {};
|
||||
return { AnimatePresence: ({ children }: any) => children, motion: new Proxy({}, { get: (_, tag: string) => cache[tag] ||= React.forwardRef(function MotionElement({ children, ...props }: any, ref) { return React.createElement(tag, { ...Object.fromEntries(Object.entries(props).filter(([key]) => !['initial', 'animate', 'exit', 'transition', 'whileHover', 'whileTap', 'whileInView', 'viewport', 'layout'].includes(key))), ref }, children); }) }) };
|
||||
});
|
||||
afterEach(cleanup);
|
||||
|
||||
const post = (id: string, dates: Partial<BlogPostItem> = {}): BlogPostItem => ({
|
||||
id, slug: id, title: `Article ${id}`, excerpt: 'Health guide', image: '/a.png',
|
||||
author: 'Author', content: '', date: '۱۴۰۵/۸/۳', categoryId: 'health',
|
||||
tags: [{ id: 'tag', name: 'health' }], ...dates,
|
||||
});
|
||||
const posts = [
|
||||
post('middle', { publishedAt: '2026-10-24T12:00:00Z', createdAt: '2026-01-01T00:00:00Z', viewCount: 30 }),
|
||||
post('old', { publishedAt: '2026-10-23T12:00:00Z', createdAt: '2026-10-26T00:00:00Z', viewCount: 80 }),
|
||||
post('new', { createdAt: '2026-10-25T12:00:00Z', viewCount: 10 }),
|
||||
];
|
||||
const titles = () => screen.getAllByRole('link').filter(link => link.getAttribute('href')?.startsWith('/blog/')).map(link => link.querySelector('h2,h3')?.textContent);
|
||||
|
||||
describe('BlogPage sorting', () => {
|
||||
it('defaults to newest using raw publication time with createdAt fallback, not the Persian display date', async () => {
|
||||
await act(async () => { render(<BlogPage blogs={posts} />); });
|
||||
expect(titles()).toEqual(['Article new', 'Article middle', 'Article old']);
|
||||
expect(posts.map(post => post.id)).toEqual(['middle', 'old', 'new']);
|
||||
});
|
||||
it('switches to oldest using publication rather than creation or localized dates', async () => {
|
||||
await act(async () => { render(<BlogPage blogs={posts} />); });
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'oldest' } });
|
||||
expect(titles()).toEqual(['Article old', 'Article middle', 'Article new']);
|
||||
});
|
||||
it('supports exactly newest, oldest and most_viewed, keeping popularity independent of dates', async () => {
|
||||
await act(async () => { render(<BlogPage blogs={posts} />); });
|
||||
expect(screen.getAllByRole('option').map(option => option.getAttribute('value'))).toEqual(['newest', 'oldest', 'most_viewed']);
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'most_viewed' } });
|
||||
expect(titles()).toEqual(['Article old', 'Article middle', 'Article new']);
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'newest' } });
|
||||
expect(titles()).toEqual(['Article new', 'Article middle', 'Article old']);
|
||||
});
|
||||
it('preserves featured priority, combined filters and six-at-a-time pagination while sorting', async () => {
|
||||
const collection = Array.from({ length: 10 }, (_, index) => post(String(index), {
|
||||
publishedAt: `2026-10-${String(index + 10).padStart(2, '0')}T12:00:00Z`,
|
||||
featured: index === 2,
|
||||
}));
|
||||
await act(async () => { render(<BlogPage blogs={[...collection, post('excluded', { categoryId: 'other' })]} categories={[{ id: 'health', name: 'Health', slug: 'health' }]} />); });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Health' }));
|
||||
fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماریها، ویتامینها...'), { target: { value: 'Health guide' } });
|
||||
fireEvent.click(screen.getByRole('button', { name: '#health' }));
|
||||
expect(titles()).toEqual(['Article 2', 'Article 9', 'Article 8', 'Article 7', 'Article 6', 'Article 5', 'Article 4']);
|
||||
fireEvent.click(screen.getByRole('button', { name: /مشاهده ۶ مقاله بیشتر/ }));
|
||||
expect(titles()).toHaveLength(10);
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'oldest' } });
|
||||
expect(titles()).toEqual(['Article 2', 'Article 0', 'Article 1', 'Article 3', 'Article 4', 'Article 5', 'Article 6', 'Article 7', 'Article 8', 'Article 9']);
|
||||
expect(screen.queryByText('Article excluded')).not.toBeInTheDocument();
|
||||
});
|
||||
it('keeps equal or unavailable raw dates stable without parsing localized display strings', async () => {
|
||||
await act(async () => { render(<BlogPage blogs={[post('missing'), post('also-missing'), ...posts]} />); });
|
||||
expect(titles()).toEqual(['Article new', 'Article middle', 'Article old', 'Article missing', 'Article also-missing']);
|
||||
fireEvent.change(screen.getByRole('combobox'), { target: { value: 'oldest' } });
|
||||
expect(titles()).toEqual(['Article missing', 'Article also-missing', 'Article old', 'Article middle', 'Article new']);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user