Skip to main content

tests/javascript/test_chives_pagination.py

1"""
2Tests for the <chives-pagination-nav> web component.
3"""
5import json
6from typing import Any
8from playwright.sync_api import expect, Page
9import pytest
12def apply_pagination(
13 page: Page, *, config: dict[str, Any], url_query: str, items: Any
14) -> None:
15 """
16 Render a list of items and the pagination component on the page.
17 """
18 page.goto("about:blank")
20 with open("javascript/chives-pagination.js") as f:
21 component_js = f.read()
23 page.evaluate(
24 """
25 %s
26 const config = %s;
27 const searchParams = new URLSearchParams(%s);
28 const pagination = new ChivesPagination(config, searchParams);
30 const items = %s;
31 const itemsToShow = pagination.apply(items);
33 const listOfItems = document.createElement("p");
34 listOfItems.innerText = JSON.stringify(itemsToShow);
35 document.body.appendChild(listOfItems);
37 renderPaginationNav({
38 "querySelector": "body",
39 totalItems: items.length,
40 pagination,
41 searchParams,
42 });
43 """
44 % (component_js, json.dumps(config), json.dumps(url_query), json.dumps(items))
45 )
48@pytest.mark.parametrize(
49 "url_query, expected_items, expected_nav",
50 [
51 (
52 "?page=1",
53 "[1,2,3,4,5]",
54 '<nav class="chives_pagination">'
55 '<span class="page_indicator">Page 1 of 3</span>'
56 '<a href="?page=2">next →</a>'
57 "</nav>",
58 ),
59 (
60 "?page=2",
61 "[6,7,8,9,10]",
62 '<nav class="chives_pagination">'
63 '<a href="?page=1">← previous</a>'
64 '<span class="page_indicator">Page 2 of 3</span>'
65 '<a href="?page=3">next →</a>'
66 "</nav>",
67 ),
68 (
69 "?page=3",
70 "[11,12,13,14,15]",
71 '<nav class="chives_pagination">'
72 '<a href="?page=2">← previous</a>'
73 '<span class="page_indicator">Page 3 of 3</span>'
74 "</nav>",
75 ),
76 (
77 "?page=10",
78 "[]",
79 '<nav class="chives_pagination">'
80 '<a href="?page=3">← previous</a>'
81 '<span class="page_indicator">Page 10 of 3</span>'
82 "</nav>",
83 ),
84 ],
86def test_render_basic_pagination(
87 page: Page, url_query: str, expected_items: str, expected_nav: str
88) -> None:
89 """
90 The <chives-pagination> component renders basic pagination controls.
91 """
92 apply_pagination(
93 page,
94 config={"perPage": 5},
95 url_query=url_query,
96 items=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
97 )
99 items_elem = page.locator("p")
100 assert items_elem.inner_text() == expected_items
102 pagination_elem = page.locator("chives-pagination-nav")
103 expect(pagination_elem).to_be_visible()
104 assert pagination_elem.inner_html() == expected_nav
107def test_no_pagination_element_if_single_page(page: Page) -> None:
108 """
109 If there's only a single page, no navigation controls are shown.
110 """
111 apply_pagination(
112 page,
113 config={"perPage": 100},
114 url_query="",
115 items=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
116 )
118 pagination_elem = page.locator("chives-pagination-nav")
119 expect(pagination_elem.locator("chives_pagination")).not_to_be_visible()