Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test/add more table test #527

Merged
merged 11 commits into from
Jan 31, 2025
Merged

test/add more table test #527

merged 11 commits into from
Jan 31, 2025

Conversation

cycleccc
Copy link
Collaborator

@cycleccc cycleccc commented Jan 27, 2025

Changes Overview

Implementation Approach

Testing Done

Verification Steps

Additional Notes

Checklist

  • I have created a changeset for this PR if necessary.
  • My changes do not break the library.
  • I have added tests where applicable.
  • I have followed the project guidelines.
  • I have fixed any lint issues.

Related Issues

Summary by CodeRabbit

  • Tests
    • Added comprehensive test suites for table module utilities
    • Introduced tests for:
      • Point class functionality
      • Random string generation
      • Virtual DOM style manipulation
      • Table cell row identification
      • Enhanced validation for parsing tables with merged children

Copy link
Contributor

coderabbitai bot commented Jan 27, 2025

Walkthrough

This pull request introduces new test suites for various functionalities within the table module. It includes tests for the isCellInFirstRow function, the Point class, the genRandomStr function, and the addVnodeStyle function. The changes aim to enhance test coverage and validate the correctness of these utility functions and their interactions within the text editor's table context.

Changes

File Change Summary
packages/table-module/__tests__/helper.test.ts Added test suite with setEditorSelection helper function and tests for isCellInFirstRow functionality
packages/table-module/__tests__/utils/point.test.ts Added comprehensive tests for Point class, covering instantiation, valueOf method, and point equality
packages/table-module/__tests__/utils/util.test.ts Added tests for genRandomStr function, verifying random string generation with different prefixes
packages/table-module/__tests__/utils/vdom.test.ts Added tests for addVnodeStyle function, checking style addition and merging for virtual nodes
packages/table-module/__tests__/parse-html.test.ts Added test case for parsing table elements with merged children in parseElemHtml function

Possibly related PRs

Poem

🐰 In the world of tables, we hop with glee,
Testing our functions, as swift as can be!
Points and styles dance, strings generated,
Our code's a delight, thoroughly celebrated!
With each little test, our confidence grows,
A rabbit's joy in the code that flows! 🧪


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f16956 and b5ddd8e.

📒 Files selected for processing (1)
  • packages/table-module/__tests__/parse-html.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/table-module/tests/parse-html.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: test-e2e

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (5)
packages/table-module/__tests__/utils/util.test.ts (1)

3-23: Test suite looks good, consider adding edge cases.

The test cases cover the basic functionality well. Consider adding:

  1. Edge case for empty prefix
  2. Test for consistent string format (e.g., length, character set)
  3. Multiple consecutive calls to strengthen uniqueness test
 describe('genRandomStr', () => {
   // ... existing tests ...
+
+  it('should handle empty prefix', () => {
+    const result = genRandomStr('')
+    expect(result).toMatch(/^-/)
+  })
+
+  it('should generate strings with consistent format', () => {
+    const result = genRandomStr()
+    expect(result).toMatch(/^r-[a-zA-Z0-9]{8}$/)
+  })
+
+  it('should generate multiple unique strings', () => {
+    const results = new Set(Array.from({ length: 100 }, () => genRandomStr()))
+    expect(results.size).toBe(100)
+  })
 })
packages/table-module/__tests__/utils/point.test.ts (1)

3-31: Enhance Point class test coverage.

While the basic functionality is well tested, consider adding:

  1. Edge cases with zero/negative coordinates
  2. Tests to ensure Point instances are immutable
  3. Tests for error handling (e.g., non-numeric inputs)
 describe('Point', () => {
   // ... existing tests ...
+
+  test('should handle zero and negative coordinates', () => {
+    const point1 = new Point(0, 0)
+    const point2 = new Point(-1, -2)
+    
+    expect(point1.x).toBe(0)
+    expect(point1.y).toBe(0)
+    expect(point2.x).toBe(-1)
+    expect(point2.y).toBe(-2)
+  })
+
+  test('should be immutable', () => {
+    const point = new Point(1, 2)
+    expect(() => {
+      // @ts-expect-error Testing runtime immutability
+      point.x = 3
+    }).toThrow()
+  })
+
+  test('should validate numeric inputs', () => {
+    expect(() => {
+      // @ts-expect-error Testing runtime type checking
+      new Point('1', '2')
+    }).toThrow()
+  })
 })
packages/table-module/__tests__/utils/vdom.test.ts (1)

5-32: Expand vdom style manipulation test coverage.

The current tests cover basic scenarios well. Consider adding:

  1. Edge cases with null/undefined styles
  2. Style property overwriting behavior
  3. Complex nested style objects
 describe('addVnodeStyle', () => {
   // ... existing tests ...
+
+  it('should handle null/undefined styles gracefully', () => {
+    const vnode: VNode = { data: {} } as VNode
+    addVnodeStyle(vnode, null as any)
+    expect(vnode.data?.style).toEqual({})
+
+    addVnodeStyle(vnode, undefined as any)
+    expect(vnode.data?.style).toEqual({})
+  })
+
+  it('should properly overwrite existing style properties', () => {
+    const vnode: VNode = h('div', { style: { color: 'blue', fontSize: '12px' } })
+    addVnodeStyle(vnode, { color: 'red' })
+    expect(vnode.data?.style).toEqual({ color: 'red', fontSize: '12px' })
+  })
+
+  it('should handle complex nested style objects', () => {
+    const vnode: VNode = h('div', { 
+      style: { 
+        transform: 'scale(1)',
+        transition: 'all 0.3s'
+      } 
+    })
+    addVnodeStyle(vnode, { 
+      transform: 'scale(1.1) rotate(45deg)',
+      animation: 'fade 0.3s'
+    })
+    expect(vnode.data?.style).toEqual({
+      transform: 'scale(1.1) rotate(45deg)',
+      transition: 'all 0.3s',
+      animation: 'fade 0.3s'
+    })
+  })
 })
packages/table-module/__tests__/helper.test.ts (2)

8-16: Add JSDoc comments to helper function.

The setEditorSelection helper function would benefit from documentation explaining its purpose and parameters.

+/**
+ * Helper function to set the editor's selection state during tests
+ * @param editor The editor instance
+ * @param selection Optional selection state, defaults to start of document
+ */
 function setEditorSelection(
   editor: core.IDomEditor,
   selection: slate.Selection = {

19-92: Consider extracting test fixture data.

The large content object could be moved to a separate fixture file to improve test readability.

Consider creating a new file __fixtures__/table-content.ts and moving the content object there.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b2ffc7 and 9288bf1.

📒 Files selected for processing (4)
  • packages/table-module/__tests__/helper.test.ts (1 hunks)
  • packages/table-module/__tests__/utils/point.test.ts (1 hunks)
  • packages/table-module/__tests__/utils/util.test.ts (1 hunks)
  • packages/table-module/__tests__/utils/vdom.test.ts (1 hunks)
🧰 Additional context used
🪛 ESLint
packages/table-module/__tests__/helper.test.ts

[error] 5-5: 'TableCellElement' is defined but never used.

(@typescript-eslint/no-unused-vars)

editor.selection = selection
}

describe('hasCommon', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Update describe block name to match tested functionality.

The describe block name 'hasCommon' doesn't match the actual functionality being tested (isCellInFirstRow).

-describe('hasCommon', () => {
+describe('isCellInFirstRow', () => {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe('hasCommon', () => {
describe('isCellInFirstRow', () => {

import * as slate from 'slate'

import createEditor from '../../../tests/utils/create-editor'
import { TableCellElement, TableElement } from '../src/module/custom-types'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Remove unused import.

The TableCellElement import is not being used in the test file.

-import { TableCellElement, TableElement } from '../src/module/custom-types'
+import { TableElement } from '../src/module/custom-types'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { TableCellElement, TableElement } from '../src/module/custom-types'
import { TableElement } from '../src/module/custom-types'
🧰 Tools
🪛 ESLint

[error] 5-5: 'TableCellElement' is defined but never used.

(@typescript-eslint/no-unused-vars)

Comment on lines 98 to 107
it('should return true if paths have a common ancestor of type table', () => {
const result = isCellInFirstRow(editor, (editor.children[1] as TableElement).children[0].children[0])

expect(result).toBe(true)
// @Todo: test other cases
// @ts-ignore
const result1 = isCellInFirstRow(editor, editor.children[1].children[0])

expect(result1).toBe(false)
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve test coverage and remove @ts-ignore.

The test suite needs improvement:

  1. The TODO comment indicates missing test cases
  2. Using @ts-ignore should be avoided
  3. Test description could be more specific
-  it('should return true if paths have a common ancestor of type table', () => {
+  it('should correctly identify cells in the first row', () => {
     const result = isCellInFirstRow(editor, (editor.children[1] as TableElement).children[0].children[0])
     expect(result).toBe(true)
-    // @Todo: test other cases
-    // @ts-ignore
-    const result1 = isCellInFirstRow(editor, editor.children[1].children[0])
-    expect(result1).toBe(false)
+
+    // Test cell in second row
+    const secondRowCell = (editor.children[1] as TableElement).children[1].children[0]
+    expect(isCellInFirstRow(editor, secondRowCell)).toBe(false)
+
+    // Test non-cell element
+    const nonCellElement = editor.children[0]
+    expect(isCellInFirstRow(editor, nonCellElement as any)).toBe(false)
   })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('should return true if paths have a common ancestor of type table', () => {
const result = isCellInFirstRow(editor, (editor.children[1] as TableElement).children[0].children[0])
expect(result).toBe(true)
// @Todo: test other cases
// @ts-ignore
const result1 = isCellInFirstRow(editor, editor.children[1].children[0])
expect(result1).toBe(false)
})
it('should correctly identify cells in the first row', () => {
const result = isCellInFirstRow(editor, (editor.children[1] as TableElement).children[0].children[0])
expect(result).toBe(true)
// Test cell in second row
const secondRowCell = (editor.children[1] as TableElement).children[1].children[0]
expect(isCellInFirstRow(editor, secondRowCell)).toBe(false)
// Test non-cell element
const nonCellElement = editor.children[0]
expect(isCellInFirstRow(editor, nonCellElement as any)).toBe(false)
})

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/table-module/__tests__/helper.test.ts (1)

98-112: Consider breaking down the test cases for better organization.

While the test cases cover important scenarios, they could be better organized for clarity and maintainability.

Consider splitting into separate test cases:

-  it('should correctly identify cells in the first row', () => {
-    const result = isCellInFirstRow(editor, (editor.children[1] as TableElement).children[0].children[0])
-    expect(result).toBe(true)
-
-    // Test cell in second row
-    const secondRowCell = (editor.children[1] as TableElement).children[1].children[0]
-    expect(isCellInFirstRow(editor, secondRowCell)).toBe(false)
-
-    // Test non-cell element
-    const nonCellElement = editor.children[0]
-    expect(isCellInFirstRow(editor, nonCellElement as any)).toBe(false)
-  })
+  describe('isCellInFirstRow', () => {
+    it('should return true for cells in the first row', () => {
+      const firstRowCell = (editor.children[1] as TableElement).children[0].children[0]
+      expect(isCellInFirstRow(editor, firstRowCell)).toBe(true)
+    })
+
+    it('should return false for cells in other rows', () => {
+      const secondRowCell = (editor.children[1] as TableElement).children[1].children[0]
+      expect(isCellInFirstRow(editor, secondRowCell)).toBe(false)
+    })
+
+    it('should return false for non-cell elements', () => {
+      const nonCellElement = editor.children[0]
+      expect(isCellInFirstRow(editor, nonCellElement as any)).toBe(false)
+    })
+  })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9288bf1 and 2056bba.

📒 Files selected for processing (1)
  • packages/table-module/__tests__/helper.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: test-e2e
🔇 Additional comments (2)
packages/table-module/__tests__/helper.test.ts (2)

1-16: LGTM! Clean imports and well-defined helper function.

The imports are minimal and necessary, and the setEditorSelection helper function is well-typed with good defaults.


18-96: LGTM! Well-structured test data.

The test content provides a comprehensive table structure with header cells, multiple rows, and proper dimensions. The setup is thorough and matches real-world scenarios.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/table-module/__tests__/parse-html.test.ts (1)

100-147: Improve test data readability with constants and documentation.

While the test data structure is comprehensive, it could be more maintainable and self-documenting.

Consider extracting common properties and adding documentation:

+// Common cell properties for merged table cells
+const DEFAULT_CELL_PROPS = {
+  isHeader: false,
+  width: 'auto',
+  hidden: false,
+  borderWidth: '1',
+  borderStyle: 'solid',
+  borderColor: '#ccc',
+}
+
+// Empty text node commonly used in cells
+const EMPTY_TEXT_NODE = { text: '' }
+
 const mergeChildren = [
   {
     type: 'table-row',
     children: [
       {
         type: 'table-cell',
-        isHeader: false,
+        ...DEFAULT_CELL_PROPS,
         colSpan: 2,
         rowSpan: 1,
-        width: 'auto',
-        children: [{ text: '' }],
-        hidden: false,
-        borderWidth: '1',
-        borderStyle: 'solid',
-        borderColor: '#ccc',
+        children: [EMPTY_TEXT_NODE],
       },
       {
         type: 'table-cell',
-        children: [{ text: '' }],
+        children: [EMPTY_TEXT_NODE],
         hidden: true,
       },
       {
         type: 'table-cell',
-        isHeader: false,
+        ...DEFAULT_CELL_PROPS,
         colSpan: 1,
         rowSpan: 1,
-        width: 'auto',
-        children: [{ text: '' }],
-        hidden: true,
-        borderWidth: '1',
-        borderStyle: 'solid',
-        borderColor: '#ccc',
+        children: [EMPTY_TEXT_NODE],
+        hidden: true,
       },
     ],
   },
 ]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2056bba and 9f16956.

📒 Files selected for processing (1)
  • packages/table-module/__tests__/parse-html.test.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: test
  • GitHub Check: test-e2e

Comment on lines 158 to 163
expect(parseTableHtmlConf.parseElemHtml($table[0], mergeChildren, editor)).toEqual({
type: 'table',
width: '100%',
mergeChildren,
height: 0,
})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add a descriptive test case for merged cells.

The test case for merged cells should be in its own it block with a descriptive name.

Consider restructuring the test:

-expect(parseTableHtmlConf.parseElemHtml($table[0], mergeChildren, editor)).toEqual({
-  type: 'table',
-  width: '100%',
-  mergeChildren,
-  height: 0,
-})

+it('should parse table with merged cells', () => {
+  const $table = $('<table style="width: 100%;"></table>')
+  expect(parseTableHtmlConf.parseElemHtml($table[0], mergeChildren, editor)).toEqual({
+    type: 'table',
+    width: '100%',
+    mergeChildren,
+    height: 0,
+  })
+})

Committable suggestion skipped: line range outside the PR's diff.

@cycleccc cycleccc merged commit cc3bcbe into master Jan 31, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant