pages_know_info.test.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. import { JSDOM } from 'jsdom'
  2. import React from 'react'
  3. import {render, waitFor, within} from '@testing-library/react'
  4. import {userEvent} from '@testing-library/user-event'
  5. import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
  6. import { createBrowserRouter, RouterProvider, Navigate } from 'react-router'
  7. import {
  8. assertEquals,
  9. assertExists,
  10. assertNotEquals,
  11. assertRejects,
  12. assert,
  13. } from "https://deno.land/std@0.217.0/assert/mod.ts";
  14. import axios from 'axios';
  15. import { KnowInfoPage } from "./pages_know_info.tsx"
  16. import { AuthProvider } from './hooks_sys.tsx'
  17. import { ProtectedRoute } from './components_protected_route.tsx'
  18. // 拦截React DOM中的attachEvent和detachEvent错误
  19. const originalError = console.error;
  20. console.error = (...args) => {
  21. // 过滤掉attachEvent和detachEvent相关的错误
  22. if (args[0] instanceof Error) {
  23. if (args[0].message?.includes('attachEvent is not a function') ||
  24. args[0].message?.includes('detachEvent is not a function')) {
  25. return; // 不输出这些错误
  26. }
  27. } else if (typeof args[0] === 'string') {
  28. if (args[0].includes('attachEvent is not a function') ||
  29. args[0].includes('detachEvent is not a function')) {
  30. return; // 不输出这些错误
  31. }
  32. }
  33. originalError(...args);
  34. };
  35. // // 配置Testing Library的eventWrapper来处理这个问题
  36. // configure({
  37. // eventWrapper: (cb) => {
  38. // try {
  39. // return cb();
  40. // } catch (error) {
  41. // console.log('eventWrapper', cb)
  42. // // 忽略attachEvent和detachEvent相关的错误
  43. // if (error instanceof Error &&
  44. // (error.message?.includes('attachEvent is not a function') ||
  45. // error.message?.includes('detachEvent is not a function'))) {
  46. // // 忽略这个错误并返回一个默认值
  47. // return undefined;
  48. // }
  49. // // 其他错误正常抛出
  50. // throw error;
  51. // }
  52. // }
  53. // });
  54. const queryClient = new QueryClient()
  55. const dom = new JSDOM(`<body></body>`, {
  56. runScripts: "dangerously",
  57. pretendToBeVisual: true,
  58. url: "http://localhost",
  59. });
  60. // 模拟浏览器环境
  61. globalThis.window = dom.window;
  62. globalThis.document = dom.window.document;
  63. // 添加必要的 DOM 配置
  64. globalThis.Node = dom.window.Node;
  65. globalThis.Document = dom.window.Document;
  66. globalThis.HTMLInputElement = dom.window.HTMLInputElement;
  67. globalThis.HTMLButtonElement = dom.window.HTMLButtonElement;
  68. // 定义浏览器环境所需的类
  69. globalThis.Element = dom.window.Element;
  70. globalThis.HTMLElement = dom.window.HTMLElement;
  71. globalThis.ShadowRoot = dom.window.ShadowRoot;
  72. globalThis.SVGElement = dom.window.SVGElement;
  73. // 模拟 getComputedStyle
  74. globalThis.getComputedStyle = (elt) => {
  75. const style = new dom.window.CSSStyleDeclaration();
  76. style.getPropertyValue = () => '';
  77. return style;
  78. };
  79. // 模拟matchMedia函数
  80. globalThis.matchMedia = (query) => ({
  81. matches: query.includes('max-width'),
  82. media: query,
  83. onchange: null,
  84. addListener: () => {},
  85. removeListener: () => {},
  86. addEventListener: () => {},
  87. removeEventListener: () => {},
  88. dispatchEvent: () => false,
  89. });
  90. // 模拟动画相关API
  91. globalThis.AnimationEvent = globalThis.AnimationEvent || dom.window.Event;
  92. globalThis.TransitionEvent = globalThis.TransitionEvent || dom.window.Event;
  93. // 模拟requestAnimationFrame
  94. globalThis.requestAnimationFrame = globalThis.requestAnimationFrame || ((cb) => setTimeout(cb, 0));
  95. globalThis.cancelAnimationFrame = globalThis.cancelAnimationFrame || clearTimeout;
  96. // 设置浏览器尺寸相关方法
  97. window.resizeTo = (width, height) => {
  98. window.innerWidth = width || window.innerWidth;
  99. window.innerHeight = height || window.innerHeight;
  100. window.dispatchEvent(new Event('resize'));
  101. };
  102. window.scrollTo = () => {};
  103. localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxIiwidXNlcm5hbWUiOiJhZG1pbiIsInNlc3Npb25JZCI6Ijk4T2lzTW5SMm0zQ0dtNmo4SVZrNyIsInJvbGVJbmZvIjpudWxsLCJpYXQiOjE3NDQzNjIzNTUsImV4cCI6MTc0NDQ0ODc1NX0.k1Ld7qWAZmdzsbjmrl_0ec1FqF_GimaOuQIic4znRtc');
  104. axios.defaults.baseURL = 'https://23957.dev.d8dcloud.com'
  105. const customScreen = within(document.body);
  106. // 应用入口组件
  107. const App = () => {
  108. // 路由配置
  109. const router = createBrowserRouter([
  110. {
  111. path: '/',
  112. element: (
  113. <ProtectedRoute>
  114. <KnowInfoPage />
  115. </ProtectedRoute>
  116. )
  117. },
  118. ]);
  119. return <RouterProvider router={router} />
  120. };
  121. // 使用异步测试处理组件渲染
  122. Deno.test({
  123. name: '知识库管理页面测试',
  124. fn: async (t) => {
  125. // 存储所有需要清理的定时器
  126. const timers: number[] = [];
  127. const originalSetTimeout = globalThis.setTimeout;
  128. const originalSetInterval = globalThis.setInterval;
  129. // 重写定时器方法以跟踪所有创建的定时器
  130. globalThis.setTimeout = ((callback, delay, ...args) => {
  131. const id = originalSetTimeout(callback, delay, ...args);
  132. timers.push(id);
  133. return id;
  134. }) as typeof setTimeout;
  135. globalThis.setInterval = ((callback, delay, ...args) => {
  136. const id = originalSetInterval(callback, delay, ...args);
  137. timers.push(id);
  138. return id;
  139. }) as typeof setInterval;
  140. // 清理函数
  141. const cleanup = () => {
  142. for (const id of timers) {
  143. clearTimeout(id);
  144. clearInterval(id);
  145. }
  146. // 恢复原始定时器方法
  147. globalThis.setTimeout = originalSetTimeout;
  148. globalThis.setInterval = originalSetInterval;
  149. };
  150. try {
  151. // 渲染组件
  152. const {
  153. findByText, findByPlaceholderText, queryByText,
  154. findByRole, findAllByRole, findByLabelText, findAllByText, debug,
  155. queryByRole
  156. } = render(
  157. <QueryClientProvider client={queryClient}>
  158. <AuthProvider>
  159. <App />
  160. </AuthProvider>
  161. </QueryClientProvider>
  162. );
  163. // 测试1: 基本渲染
  164. await t.step('应正确渲染页面元素', async () => {
  165. await waitFor(async () => {
  166. const title = await findByText(/知识库管理/i);
  167. assertExists(title, '未找到知识库管理标题');
  168. }, {
  169. timeout: 1000 * 5,
  170. });
  171. });
  172. // 初始加载表格数据
  173. await t.step('初始加载表格数据', async () => {
  174. await waitFor(async () => {
  175. const table = await findByRole('table');
  176. const rows = await within(table).findAllByRole('row');
  177. // 应该大于2行
  178. assert(rows.length > 2, '表格没有数据'); // 1是表头行 2是数据行
  179. }, {
  180. timeout: 1000 * 5,
  181. });
  182. });
  183. // 测试2: 搜索表单功能
  184. await t.step('搜索表单应正常工作', async () => {
  185. // 确保在正确的测试环境中设置 userEvent
  186. const user = userEvent.setup({
  187. document: dom.window.document,
  188. delay: 0
  189. });
  190. // 直接查找标题搜索输入框和搜索按钮
  191. const searchInput = await findByPlaceholderText(/请输入文章标题/i) as HTMLInputElement;
  192. const searchButton = await findByText(/搜 索/i);
  193. assertExists(searchInput, '未找到搜索输入框');
  194. assertExists(searchButton, '未找到搜索按钮');
  195. // 输入搜索内容
  196. await user.type(searchInput, '数据分析')
  197. assertEquals(searchInput.value, '数据分析', '搜索输入框值未更新');
  198. // 提交搜索
  199. await user.click(searchButton);
  200. let rows: HTMLElement[] = [];
  201. const table = await findByRole('table');
  202. assertExists(table, '未找到数据表格');
  203. // 等待表格刷新并验证
  204. await waitFor(async () => {
  205. rows = await within(table).findAllByRole('row');
  206. assert(rows.length === 2, '表格未刷新');
  207. }, {
  208. timeout: 1000 * 5,
  209. onTimeout: () => new Error('等待表格刷新超时')
  210. });
  211. // 等待搜索结果并验证
  212. await waitFor(async () => {
  213. rows = await within(table).findAllByRole('row');
  214. assert(rows.length > 2, '表格没有数据');
  215. }, {
  216. timeout: 1000 * 5,
  217. onTimeout: () => new Error('等待搜索结果超时')
  218. });
  219. // 检查至少有一行包含"数据分析"
  220. const matchResults = await Promise.all(rows.map(async row => {
  221. try{
  222. const cells = await within(row).findAllByRole('cell');
  223. return cells.some(cell => {
  224. return cell.textContent?.includes('数据分析')
  225. });
  226. } catch (error: unknown) {
  227. // console.error('搜索结果获取失败', error)
  228. return false
  229. }
  230. }))
  231. // console.log('matchResults', matchResults)
  232. const hasMatch = matchResults.some(result => result);
  233. assert(hasMatch, '搜索结果中没有找到包含"数据分析"的文章');
  234. });
  235. // 测试3: 表格数据加载
  236. await t.step('表格应加载并显示数据', async () => {
  237. // 等待数据加载完成或表格出现,最多等待5秒
  238. await waitFor(async () => {
  239. // 检查加载状态是否消失
  240. const loading = queryByText(/正在加载数据/i);
  241. if (loading) {
  242. throw new Error('数据仍在加载中');
  243. }
  244. // 检查表格是否出现
  245. const table = await findByRole('table');
  246. assertExists(table, '未找到数据表格');
  247. // 检查表格是否有数据行
  248. const rows = await within(table).findAllByRole('row');
  249. assertNotEquals(rows.length, 1, '表格没有数据行'); // 1是表头行
  250. }, {
  251. timeout: 5000, // 5秒超时
  252. onTimeout: (error) => {
  253. return new Error(`数据加载超时: ${error.message}`);
  254. }
  255. });
  256. });
  257. // 测试4: 添加文章功能
  258. await t.step('应能打开添加文章模态框', async () => {
  259. // 确保在正确的测试环境中设置 userEvent
  260. const user = userEvent.setup({
  261. document: dom.window.document,
  262. delay: 0
  263. });
  264. const addButton = await findByText(/添加文章/i);
  265. assertExists(addButton, '未找到添加文章按钮');
  266. await user.click(addButton);
  267. // 找到模态框
  268. const modal = await findByRole('dialog');
  269. assertExists(modal, '未找到模态框');
  270. const modalTitle = await within(modal).findByText(/添加知识库文章/i);
  271. assertExists(modalTitle, '未找到添加文章模态框');
  272. // 验证表单字段
  273. const titleInput = await within(modal).findByPlaceholderText(/请输入文章标题/i);
  274. assertExists(titleInput, '未找到标题输入框');
  275. const contentInput = await within(modal).findByPlaceholderText(/请输入文章内容/i);
  276. assertExists(contentInput, '未找到文章内容输入框');
  277. // 取消
  278. const cancelButton = await within(modal).findByText(/取 消/i);
  279. assertExists(cancelButton, '未找到取消按钮');
  280. await user.click(cancelButton);
  281. // 验证模态框是否关闭
  282. await waitFor(async () => {
  283. const modalTitle = await within(modal).findByText(/添加知识库文章/i);
  284. assertExists(!modalTitle, '模态框未关闭');
  285. }, {
  286. timeout: 1000 * 5,
  287. onTimeout: () => new Error('等待模态框关闭超时')
  288. });
  289. });
  290. // 测试5: 完整添加文章流程
  291. await t.step('应能完整添加一篇文章', async () => {
  292. // 确保在正确的测试环境中设置 userEvent
  293. const user = userEvent.setup({
  294. document: dom.window.document,
  295. delay: 0
  296. });
  297. // 打开添加模态框
  298. const addButton = await findByText(/添加文章/i);
  299. assertExists(addButton, '未找到添加文章按钮');
  300. await user.click(addButton);
  301. // 找到模态框
  302. const modal = await findByRole('dialog');
  303. assertExists(modal, '未找到模态框');
  304. const modalTitle = await within(modal).findByText(/添加知识库文章/i);
  305. assertExists(modalTitle, '未找到添加文章模态框');
  306. // 确保上一个测试的输入框值不会影响这个测试
  307. // 在模态框内查找标题和内容输入框
  308. const titleInput = await within(modal).findByPlaceholderText(/请输入文章标题/i) as HTMLInputElement;
  309. const contentInput = await within(modal).findByPlaceholderText(/请输入文章内容/i) as HTMLTextAreaElement;
  310. const submitButton = await within(modal).findByText(/确 定/i);
  311. assertExists(titleInput, '未找到模态框中的标题输入框');
  312. assertExists(contentInput, '未找到文章内容输入框');
  313. assertExists(submitButton, '未找到提交按钮');
  314. // 先清空输入框,以防止之前的测试影响
  315. // await user.clear(titleInput);
  316. // await user.clear(contentInput);
  317. // 输入新值
  318. await user.type(titleInput, '测试文章标题');
  319. await user.type(contentInput, '这是测试文章内容');
  320. debug(titleInput);
  321. debug(contentInput);
  322. debug(submitButton);
  323. // 验证表单字段
  324. assertEquals(titleInput.value, '测试文章标题', '模态框中标题输入框值未更新');
  325. assertEquals(contentInput.value, '这是测试文章内容', '内容输入框值未更新');
  326. // 提交表单
  327. await user.click(submitButton);
  328. let rows: HTMLElement[] = [];
  329. const table = await findByRole('table');
  330. assertExists(table, '未找到数据表格');
  331. // 等待表格刷新并验证
  332. await waitFor(async () => {
  333. rows = await within(table).findAllByRole('row');
  334. assert(rows.length === 2, '表格未刷新');
  335. }, {
  336. timeout: 1000 * 5,
  337. onTimeout: () => new Error('等待表格刷新超时')
  338. });
  339. // 等待搜索结果并验证
  340. await waitFor(async () => {
  341. rows = await within(table).findAllByRole('row');
  342. assert(rows.length > 2, '表格没有数据');
  343. }, {
  344. timeout: 1000 * 5,
  345. onTimeout: () => new Error('等待搜索结果超时')
  346. });
  347. // 检查至少有一行包含"测试文章标题"
  348. const matchResults = await Promise.all(rows.map(async row => {
  349. try{
  350. const cells = await within(row).findAllByRole('cell');
  351. return cells.some(cell => {
  352. return cell.textContent?.includes('测试文章标题')
  353. });
  354. } catch (error: unknown) {
  355. // console.error('搜索结果获取失败', error)
  356. return false
  357. }
  358. }))
  359. // console.log('matchResults', matchResults)
  360. const hasMatch = matchResults.some(result => result);
  361. assert(hasMatch, '搜索结果中没有找到包含"测试文章标题"的文章');
  362. });
  363. // // 测试5: 分页功能
  364. // await t.step('应显示分页控件', async () => {
  365. // const pagination = await findByRole('navigation');
  366. // assertExists(pagination, '未找到分页控件');
  367. // const pageItems = await findAllByRole('button', { name: /1|2|3|下一页|上一页/i });
  368. // assertNotEquals(pageItems.length, 0, '未找到分页按钮');
  369. // });
  370. // // 测试6: 操作按钮
  371. // await t.step('应显示操作按钮', async () => {
  372. // const editButtons = await findAllByText(/编辑/i);
  373. // assertNotEquals(editButtons.length, 0, '未找到编辑按钮');
  374. // const deleteButtons = await findAllByText(/删除/i);
  375. // assertNotEquals(deleteButtons.length, 0, '未找到删除按钮');
  376. // });
  377. } finally {
  378. // 确保清理所有定时器
  379. cleanup();
  380. }
  381. },
  382. sanitizeOps: false, // 禁用操作清理检查
  383. sanitizeResources: false, // 禁用资源清理检查
  384. });