Skip to content

chore: unit test implementation#30

Merged
hidaytrahman merged 7 commits intomainfrom
chore/testing
Jun 15, 2025
Merged

chore: unit test implementation#30
hidaytrahman merged 7 commits intomainfrom
chore/testing

Conversation

@hidaytrahman
Copy link
Owner

@hidaytrahman hidaytrahman commented Jun 15, 2025

ref: issue: #4

Final
image

initial
image

chore: unit test implementation

Summary by CodeRabbit

  • New Features

    • Introduced a comprehensive testing setup with Jest and Testing Library, enabling unit tests and coverage reporting for the application.
    • Added detailed best practice guidelines for project development and testing.
  • Tests

    • Added unit tests for key components and views, including Footer, Navigation, StandardImageList, About, Contact, Landing, Home, Profile, and Settings.
    • Added tests for service functions and utility modules to ensure robust coverage.
  • Documentation

    • Updated README with information about test coverage thresholds.
    • Added a BEST_PRACTICES.md file outlining development and testing standards.
  • Chores

    • Updated project configuration to support testing, including TypeScript, Jest, and npm scripts.

@hidaytrahman hidaytrahman self-assigned this Jun 15, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 15, 2025

Warning

Rate limit exceeded

@hidaytrahman has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 39 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c386d57 and f93dcc8.

📒 Files selected for processing (1)
  • package.json (3 hunks)

Walkthrough

This update introduces a comprehensive testing infrastructure for a React + TypeScript + Webpack project. It adds Jest configuration with TypeScript and jsdom support, sets up global and per-file coverage thresholds, and integrates Testing Library utilities. Multiple test files are added for components, views, services, and utilities, covering rendering, user interactions, and service logic. The package.json is updated with scripts and devDependencies for testing. TypeScript configuration is updated to recognize testing types. A new best practices document is included, and the README is updated to document coverage expectations. Additionally, the createTodo service function now uses an explicit return type interface.

Sequence Diagram(s)

sequenceDiagram
    participant Tester as Developer
    participant CLI as Command Line
    participant Jest as Jest Runner
    participant App as Application Code
    participant DOM as jsdom Environment

    Tester->>CLI: Run "npm test" or "npm run test:coverage"
    CLI->>Jest: Invoke Jest with config
    Jest->>App: Load test files (tsx, ts, etc.)
    App->>DOM: Render components (via jsdom)
    App->>App: Run service/util functions
    Jest->>Jest: Collect results & coverage
    Jest->>CLI: Output test results and coverage summary
Loading

Poem

🐇
With jest and cheer, the tests appear,
Ensuring code is crisp and clear.
From Footer’s links to Profile’s face,
Each branch and line in its right place.
Thresholds set, the bar is high—
Our code and tests now reach the sky!

— A rabbit who loves to hop through coverage reports


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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: 5

🧹 Nitpick comments (11)
jest.setup.js (1)

1-1: Prefer ESM import to stay consistent with the codebase

Everywhere else you’re using ES-module syntax. Keeping the same style avoids ts-jest/ESM interop edge cases and improves tree-shaking.

-require('@testing-library/jest-dom');
+import '@testing-library/jest-dom';

If Jest is running with transform: { '^.+\\.[tj]sx?$': 'ts-jest' }, jest.setup.ts (note the extension) can be transpiled directly.

src/views/Dashboard/Settings/Settings.test.tsx (1)

6-7: Strengthen the assertion

Matching only the role is coarse-grained. Enforce the heading level to guard against accidental semantic regressions:

-expect(screen.getByRole('heading', { name: /settings/i })).toBeInTheDocument();
+expect(
+  screen.getByRole('heading', { level: 3, name: /settings/i })
+).toBeInTheDocument();
src/views/Dashboard/Home/Home.test.tsx (1)

6-8: Mirror the stronger heading check used elsewhere

Same rationale as for the Settings test—assert the heading level to avoid silent breaks in semantics.

-expect(screen.getByRole('heading', { name: /home/i })).toBeInTheDocument();
+expect(
+  screen.getByRole('heading', { level: 3, name: /home/i })
+).toBeInTheDocument();
src/components/HelloWorld.test.tsx (2)

4-7: Move the component under test to src/components/HelloWorld.tsx

Defining the component inside the test makes it impossible to reuse and skews coverage metrics. Extracting it keeps production and test code separate:

- function HelloWorld() {
-   return <div>Hello, World!</div>;
- }
+// src/components/HelloWorld.tsx
+export default function HelloWorld() {
+  return <div>Hello, World!</div>;
+}

Then in the test file:

import HelloWorld from './HelloWorld';

10-12: Use getByRole for accessibility-focused assertions

-expect(screen.getByText(/hello, world/i)).toBeInTheDocument();
+expect(
+  screen.getByRole('heading', { name: /hello, world/i })
+).toBeInTheDocument();

This keeps the accessibility contract front-and-centre.

src/views/Contact/Contact.test.tsx (1)

4-10: Consider asserting form elements or interaction paths, not only static text
Right now the test only checks for static copy that’s unlikely to regress. If the Contact view contains interactive elements (e.g. a form, submit button, validation messages), adding at least one interaction-oriented test will give the suite real value and protect against behavioural regressions.

Example quick win:

 it('renders Contact Us heading and mission text', () => {
   render(<Contact />);
   …
+  // Ensure the contact form is present
+  expect(screen.getByRole('textbox', { name: /name/i })).toBeInTheDocument();
+  expect(screen.getByRole('button', { name: /submit/i })).toBeEnabled();
 });
src/components/StandardImageList/StandardImageList.test.tsx (1)

6-12: Make the expected image count explicit to avoid false positives
expect(images.length).toBeGreaterThanOrEqual(12); will silently pass if half the data is lost but still ≥ 12. Since itemData is static, assert the exact length (or import the source array length) so that any change flags the test.

-const images = screen.getAllByRole('img');
-expect(images.length).toBeGreaterThanOrEqual(12);
+const images = screen.getAllByRole('img');
+expect(images).toHaveLength(12);          // or itemData.length if exported
src/components/Footer/Footer.test.tsx (1)

8-12: Add a security-oriented assertion for rel="noopener noreferrer"
External links opened via target="_blank" should include rel="noopener noreferrer" to prevent tab-napping. Including it in the test will ensure the attribute isn’t accidentally dropped later.

 expect(link).toHaveAttribute('target', '_blank');
+expect(link).toHaveAttribute('rel', expect.stringContaining('noopener'));
+expect(link).toHaveAttribute('rel', expect.stringContaining('noreferrer'));
src/views/Dashboard/Profile/Profile.test.tsx (2)

4-12: Isolate mocks & avoid state-bleed

A module–level jest.mock() with an embedded jest.fn() will keep the same mock instance across every test file that imports this module.
When more tests are added the captured call-history or altered return values can leak between suites.

-jest.mock('@/services/app.services', () => ({
-  fetchUser: jest.fn().mockResolvedValue({
+const fetchUserMock = jest.fn().mockResolvedValue({
     name: 'Test User',
     greet: 'Hello!',
     location: 'Test City',
     intro: 'Test intro',
     totalExperience: 5
-  })
-}));
+});
+
+jest.mock('@/services/app.services', () => ({ fetchUser: fetchUserMock }));
+
+afterEach(() => {
+  jest.resetAllMocks();
+});

Using a dedicated variable plus afterEach(jest.resetAllMocks) keeps each test hermetic and lets you add per-test overrides via mockResolvedValueOnce.


15-22: Leverage Testing-Library’s async finders for cleaner assertions

waitFor combined with multiple expectations is harder to read and, if one assertion fails early, retries stop immediately.
findBy* / findAllBy* automatically wait for the element and fail only after the timeout.

-    render(<Profile />);
-    expect(screen.getByText(/loading/i)).toBeInTheDocument();
-    await waitFor(() => {
-      expect(screen.getByRole('img', { name: 'Test User' })).toBeInTheDocument();
-      expect(screen.getByRole('heading', { name: 'Hello!' })).toBeInTheDocument();
-      expect(screen.getByText('Test intro')).toBeInTheDocument();
-    });
+    render(<Profile />);
+    expect(screen.getByText(/loading/i)).toBeInTheDocument();
+
+    expect(
+      await screen.findByRole('img', { name: 'Test User' })
+    ).toBeInTheDocument();
+    expect(
+      await screen.findByRole('heading', { name: 'Hello!' })
+    ).toBeInTheDocument();
+    expect(await screen.findByText('Test intro')).toBeInTheDocument();

This is more idiomatic and reduces flakiness.

src/views/Landing/Landing.test.tsx (1)

9-10: Replace synchronous image query with an async finder

StandardImageList loads its images asynchronously; grabbing them synchronously risks a false-negative on slow DOM updates.

-    // StandardImageList renders at least one image
-    expect(screen.getAllByRole('img').length).toBeGreaterThan(0);
+    // StandardImageList renders at least one image
+    const images = await screen.findAllByRole('img');
+    expect(images.length).toBeGreaterThan(0);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 022de17 and 3a2a79a.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (14)
  • jest.config.js (1 hunks)
  • jest.setup.js (1 hunks)
  • package.json (3 hunks)
  • src/components/Footer/Footer.test.tsx (1 hunks)
  • src/components/HelloWorld.test.tsx (1 hunks)
  • src/components/Navigation/Navigation.test.tsx (1 hunks)
  • src/components/StandardImageList/StandardImageList.test.tsx (1 hunks)
  • src/views/About/About.test.tsx (1 hunks)
  • src/views/Contact/Contact.test.tsx (1 hunks)
  • src/views/Dashboard/Home/Home.test.tsx (1 hunks)
  • src/views/Dashboard/Profile/Profile.test.tsx (1 hunks)
  • src/views/Dashboard/Settings/Settings.test.tsx (1 hunks)
  • src/views/Landing/Landing.test.tsx (1 hunks)
  • tsconfig.json (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/views/Dashboard/Home/Home.test.tsx (1)
src/views/Dashboard/Home/Home.tsx (1)
  • Home (3-7)
🔇 Additional comments (2)
src/views/Dashboard/Settings/Settings.test.tsx (1)

4-8: Add a router/provider wrapper if Settings relies on context

Many dashboard components import react-router-dom or a global theme provider. Rendering without the expected context will make the test pass now but explode once the component grows.

-    render(<Settings />);
+    render(
+      <BrowserRouter>
+        <Settings />
+      </BrowserRouter>
+    );

(Replace BrowserRouter with whatever provider the component actually requires.)

src/views/About/About.test.tsx (1)

4-12: LGTM – covers the essential static copy
The assertions hit all visible text blocks and headings; nothing blocking here.

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 (3)
src/utils/theme.utils.test.ts (1)

3-8: Consider broadening the assertions for future-proofing.

Right now the test only checks the main swatches. If theme.palette.primary.light / dark (or other palette keys) are ever added or changed, the test suite won’t catch a regression. A quick extension keeps the test meaningful without much cost:

-    expect(theme.palette.primary.main).toBe('#8A784E');
-    expect(theme.palette.secondary.main).toBe('#edf2ff');
+    expect(theme.palette.primary).toMatchObject({ main: '#8A784E' });
+    expect(theme.palette.secondary).toMatchObject({ main: '#edf2ff' });

This still protects the critical colours and leaves room for additional keys.

src/services/app.services.test.ts (2)

4-6: Move the mock declaration above imports for clarity.

jest.mock('axios') is automatically hoisted, so the code works, but placing it immediately after imports causes minor cognitive friction. Consider the canonical ordering:

import axios from 'axios';
jest.mock('axios');          // 👈 right after the import

No functional change, just readability.


35-43: Optional: add a test for the “unknown error” branch.

createTodo converts non-Error rejections to the string 'Unknown error'. A simple extra test with mockRejectedValueOnce('boom') would lock that behaviour down.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3a2a79a and 739c0af.

📒 Files selected for processing (3)
  • jest.config.js (1 hunks)
  • src/services/app.services.test.ts (1 hunks)
  • src/utils/theme.utils.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • jest.config.js
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/utils/theme.utils.test.ts (1)
src/utils/theme.utils.ts (1)
  • theme (19-28)
src/services/app.services.test.ts (1)
src/services/app.services.ts (2)
  • fetchUser (5-13)
  • createTodo (16-27)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-and-test
🔇 Additional comments (2)
src/utils/theme.utils.test.ts (1)

1-1: Import path is solid – good job.

The relative import matches the nearby theme.utils.ts implementation, so the test will resolve correctly in Jest with the current project structure.

src/services/app.services.test.ts (1)

16-24: Good negative-path coverage.

Verifying that console.error is invoked and undefined is returned on failure exercises the catch block thoroughly – nice.

@hidaytrahman hidaytrahman merged commit e604909 into main Jun 15, 2025
1 check 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