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

Testes para a função updateTrending #560

Closed
wants to merge 2 commits into from

Conversation

WillxBernardo
Copy link

@WillxBernardo WillxBernardo commented Jan 18, 2025

Descrição

Este pull request adiciona testes unitários para o método updateTrending e inclui configurações adicionais necessárias para garantir a execução correta dos testes no ambiente atual. O objetivo principal é aumentar a cobertura de testes e validar cenários críticos relacionados à atualização de tendências.

Principais mudanças:

Adição de Testes Unitários:

  • Teste com data vazia (CT1).
  • Teste com dados válidos e valores corretos (CT2).
  • Teste com dados contendo valores inválidos (CT3).
  • Teste com dados válidos, verificando chamadas ao saveTrending (CT4).
  • Mocks de Dependências Ausentes:

Criados mocks para as seguintes dependências ausentes:

  • @gitroom/nestjs-libraries/database/prisma/stars/stars.repository
  • @gitroom/nestjs-libraries/database/prisma/notifications/notification.service
  • @gitroom/nestjs-libraries/bull-mq-transport-new/client
  • Configuração Adicional do Ambiente de Testes:

Além da adição do Jest para criação de mocks e isolamento de dependências.

Summary by CodeRabbit

  • New Features

    • Added comprehensive Jest testing configuration
    • Introduced new test suite for trending updates
  • Chores

    • Updated Jest dependency to latest version
    • Added test script to run Jest
    • Enhanced TypeScript configuration to include test and source files
  • Tests

    • Implemented detailed test cases for trending update functionality

Copy link

vercel bot commented Jan 18, 2025

@WillxBernardo is attempting to deploy a commit to the Listinai Team on Vercel.

A member of the Team first needs to authorize it.

Copy link

coderabbitai bot commented Jan 18, 2025

Walkthrough

This pull request introduces configuration updates for Jest testing, enhancing the project's TypeScript testing capabilities. The changes include modifying the Jest configuration to support TypeScript, updating the package.json to include a test script, adding a new test suite for an updateTrending method, and extending the TypeScript configuration to include additional test and source files. These modifications aim to improve the project's testing infrastructure and ensure comprehensive test coverage.

Changes

File Change Summary
jest.config.ts Switched from ES module to CommonJS export, added TypeScript preset, specified Node.js test environment, defined module extensions and test matching patterns
package.json Added test script using Jest, updated Jest dependency to use caret version
tests/updateTrending.test.ts Created new test suite for YourService with updateTrending method, including various test scenarios for trending item management
tsconfig.base.json Added include property to specify additional TypeScript files for compilation

Sequence Diagram

sequenceDiagram
    participant Service as YourService
    participant StarsRepo as Stars Repository
    participant NotifyService as Notification Service

    Service->>StarsRepo: Retrieve current trending items
    Service->>Service: Compare with new trending list
    alt Changes detected
        Service->>Service: Identify removed/changed items
        Service->>NotifyService: Trigger notifications
    end
Loading

Poem

🐰 A Jest of Testing Delight 🧪

Config files dance with might,
TypeScript tests now shine so bright,
Trending items hop and play,
Mocked services lead the way,
Our code leaps with pure delight!

- Hoppy the CodeRabbit 🚀

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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

@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 (3)
jest.config.ts (1)

3-10: Consider enhancing the Jest configuration for better test coverage and specificity.

  1. Add coverage configuration to track test coverage metrics.
  2. Make test patterns more specific to avoid unintended matches.
 module.exports = {
   preset: 'ts-jest',  // Usando ts-jest para suportar TypeScript
   testEnvironment: 'node',  // Ambiente de teste para Node.js
   moduleFileExtensions: ['js', 'json', 'ts'],
   testMatch: ['**/tests/**/*.spec.ts', '**/tests/**/*.test.ts'],  // Caminho para os testes
   testPathIgnorePatterns: ['/node_modules/'],  // Ignora a pasta node_modules
   verbose: true,  // Exibe detalhes adicionais ao executar os testes
+  collectCoverage: true,
+  coverageDirectory: 'coverage',
+  coverageReporters: ['text', 'lcov'],
+  testMatch: [
+    '**/tests/**/__tests__/**/*.[jt]s?(x)',
+    '**/tests/**/?(*.)+(spec|test).[jt]s?(x)'
+  ],
 };
tests/updateTrending.test.ts (1)

4-7: Add type definitions for mocked dependencies.

The mocked dependencies should have proper TypeScript interfaces/types for better type safety.

+import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
+import { StarsRepository } from '@gitroom/nestjs-libraries/database/prisma/stars/stars.repository';
+
 // Mock das dependências
 jest.mock('@gitroom/nestjs-libraries/database/prisma/stars/stars.repository');
 jest.mock('@gitroom/nestjs-libraries/database/prisma/notifications/notification.service');
 jest.mock('@gitroom/nestjs-libraries/bull-mq-transport-new/client');
tsconfig.base.json (1)

34-39: Consider more specific patterns for test files.

The current patterns might include unnecessary files. Consider organizing tests in a more structured way.

   "include": [
-    "tests/**/*.spec.ts", 
-    "tests/**/*.test.ts",
+    "tests/**/__tests__/**/*.ts",
+    "tests/**/*.spec.ts",
+    "tests/**/*.test.ts",
     "libs/**/*.ts",
     "apps/**/*.ts"
   ]
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2b8e0bc and c96a7f1.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • jest.config.ts (1 hunks)
  • package.json (2 hunks)
  • tests/updateTrending.test.ts (1 hunks)
  • tsconfig.base.json (1 hunks)
🔇 Additional comments (1)
package.json (1)

32-33: Verify Jest version compatibility.

The caret version for Jest (^29.7.0) should be verified against other testing-related dependencies to ensure compatibility.

✅ Verification successful

Jest ecosystem dependencies are properly aligned

All Jest-related packages are using compatible versions within the 29.x range.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check versions of related testing packages
echo "Checking versions of testing-related packages:"
npm list jest jest-environment-jsdom jest-environment-node ts-jest @types/jest

Length of output: 438


Script:

#!/bin/bash
# Check if ts-jest or @types/jest are listed in package.json
cat package.json | jq '.dependencies, .devDependencies'

Length of output: 5438

return current && current.position !== p.position;
});
if (removedFromTrending.length) {
await this.notificationService.inform(Inform.Removed, removedFromTrending, language);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Define the Inform enum for better code clarity.

The Inform enum is used but not defined, which could lead to maintenance issues.

+enum Inform {
+  Removed = 1,
+  Changed = 2,
+  New = 3
+}
+
 // ... rest of the code

Also applies to: 60-60, 68-68

Comment on lines +88 to +96
test('CT1: Teste com data vazio', async () => {
const data: Array<{ name: string; position: number }> = [];

await service.updateTrending('en', 'hash1', data);

expect(mockStarsRepository.getTrendingByLanguage).not.toHaveBeenCalled();
expect(mockNotificationService.inform).not.toHaveBeenCalled();
expect(mockReplaceOrAddTrending).not.toHaveBeenCalled();
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance empty data test case.

The test case for empty data should verify that the function handles the case gracefully, but it's currently not testing the actual behavior.

-  test('CT1: Teste com data vazio', async () => {
+  test('should not process updates when trending list is empty', async () => {
     const data: Array<{ name: string; position: number }> = [];
 
     await service.updateTrending('en', 'hash1', data);
 
-    expect(mockStarsRepository.getTrendingByLanguage).not.toHaveBeenCalled();
+    expect(mockStarsRepository.getTrendingByLanguage).toHaveBeenCalledWith('en');
     expect(mockNotificationService.inform).not.toHaveBeenCalled();
     expect(mockReplaceOrAddTrending).not.toHaveBeenCalled();
   });
📝 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
test('CT1: Teste com data vazio', async () => {
const data: Array<{ name: string; position: number }> = [];
await service.updateTrending('en', 'hash1', data);
expect(mockStarsRepository.getTrendingByLanguage).not.toHaveBeenCalled();
expect(mockNotificationService.inform).not.toHaveBeenCalled();
expect(mockReplaceOrAddTrending).not.toHaveBeenCalled();
});
test('should not process updates when trending list is empty', async () => {
const data: Array<{ name: string; position: number }> = [];
await service.updateTrending('en', 'hash1', data);
expect(mockStarsRepository.getTrendingByLanguage).toHaveBeenCalledWith('en');
expect(mockNotificationService.inform).not.toHaveBeenCalled();
expect(mockReplaceOrAddTrending).not.toHaveBeenCalled();
});

Comment on lines +19 to +32
class YourService {
private _starsRepository;
private notificationService;
private replaceOrAddTrending;

constructor(
_starsRepository: any,
notificationService: any,
replaceOrAddTrending: any
) {
this._starsRepository = _starsRepository;
this.notificationService = notificationService;
this.replaceOrAddTrending = replaceOrAddTrending;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve type safety in the service class.

The service class uses any types which should be avoided for better type safety.

+interface TrendingItem {
+  name: string;
+  position: number;
+}
+
 class YourService {
-  private _starsRepository;
-  private notificationService;
-  private replaceOrAddTrending;
+  private _starsRepository: StarsRepository;
+  private notificationService: NotificationService;
+  private replaceOrAddTrending: (language: string, hash: string, arr: TrendingItem[]) => Promise<void>;

   constructor(
-    _starsRepository: any,
-    notificationService: any,
-    replaceOrAddTrending: any
+    _starsRepository: StarsRepository,
+    notificationService: NotificationService,
+    replaceOrAddTrending: (language: string, hash: string, arr: TrendingItem[]) => Promise<void>
   )

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

Comment on lines +34 to +70
async updateTrending(
language: string,
hash: string,
arr: Array<{ name: string; position: number }>
) {
const currentTrending = await this._starsRepository.getTrendingByLanguage(language);

if (currentTrending?.hash === hash) {
return;
}

if (currentTrending) {
const list: Array<{ name: string; position: number }> = JSON.parse(
currentTrending.trendingList
);
const removedFromTrending = list.filter(
(p) => !arr.find((a) => a.name === p.name)
);
const changedPosition = arr.filter((p) => {
const current = list.find((a) => a.name === p.name);
return current && current.position !== p.position;
});
if (removedFromTrending.length) {
await this.notificationService.inform(Inform.Removed, removedFromTrending, language);
}
if (changedPosition.length) {
await this.notificationService.inform(Inform.Changed, changedPosition, language);
}
}

const informNewPeople = arr.filter(
(p) => !currentTrending?.trendingList || currentTrending?.trendingList.indexOf(p.name) === -1
);

await this.notificationService.inform(Inform.New, informNewPeople, language);
await this.replaceOrAddTrending(language, hash, arr);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add input validation to updateTrending method.

The method should validate its inputs before processing to prevent invalid data.

   async updateTrending(
     language: string,
     hash: string,
     arr: Array<{ name: string; position: number }>
   ) {
+    if (!language || typeof language !== 'string') {
+      throw new Error('Invalid language parameter');
+    }
+    if (!hash || typeof hash !== 'string') {
+      throw new Error('Invalid hash parameter');
+    }
+    if (!Array.isArray(arr)) {
+      throw new Error('Invalid array parameter');
+    }
+    for (const item of arr) {
+      if (!item.name || typeof item.name !== 'string') {
+        throw new Error('Invalid item name');
+      }
+      if (typeof item.position !== 'number' || isNaN(item.position)) {
+        throw new Error('Invalid position value');
+      }
+    }
+
     const currentTrending = await this._starsRepository.getTrendingByLanguage(language);
📝 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
async updateTrending(
language: string,
hash: string,
arr: Array<{ name: string; position: number }>
) {
const currentTrending = await this._starsRepository.getTrendingByLanguage(language);
if (currentTrending?.hash === hash) {
return;
}
if (currentTrending) {
const list: Array<{ name: string; position: number }> = JSON.parse(
currentTrending.trendingList
);
const removedFromTrending = list.filter(
(p) => !arr.find((a) => a.name === p.name)
);
const changedPosition = arr.filter((p) => {
const current = list.find((a) => a.name === p.name);
return current && current.position !== p.position;
});
if (removedFromTrending.length) {
await this.notificationService.inform(Inform.Removed, removedFromTrending, language);
}
if (changedPosition.length) {
await this.notificationService.inform(Inform.Changed, changedPosition, language);
}
}
const informNewPeople = arr.filter(
(p) => !currentTrending?.trendingList || currentTrending?.trendingList.indexOf(p.name) === -1
);
await this.notificationService.inform(Inform.New, informNewPeople, language);
await this.replaceOrAddTrending(language, hash, arr);
}
async updateTrending(
language: string,
hash: string,
arr: Array<{ name: string; position: number }>
) {
if (!language || typeof language !== 'string') {
throw new Error('Invalid language parameter');
}
if (!hash || typeof hash !== 'string') {
throw new Error('Invalid hash parameter');
}
if (!Array.isArray(arr)) {
throw new Error('Invalid array parameter');
}
for (const item of arr) {
if (!item.name || typeof item.name !== 'string') {
throw new Error('Invalid item name');
}
if (typeof item.position !== 'number' || isNaN(item.position)) {
throw new Error('Invalid position value');
}
}
const currentTrending = await this._starsRepository.getTrendingByLanguage(language);
if (currentTrending?.hash === hash) {
return;
}
if (currentTrending) {
const list: Array<{ name: string; position: number }> = JSON.parse(
currentTrending.trendingList
);
const removedFromTrending = list.filter(
(p) => !arr.find((a) => a.name === p.name)
);
const changedPosition = arr.filter((p) => {
const current = list.find((a) => a.name === p.name);
return current && current.position !== p.position;
});
if (removedFromTrending.length) {
await this.notificationService.inform(Inform.Removed, removedFromTrending, language);
}
if (changedPosition.length) {
await this.notificationService.inform(Inform.Changed, changedPosition, language);
}
}
const informNewPeople = arr.filter(
(p) => !currentTrending?.trendingList || currentTrending?.trendingList.indexOf(p.name) === -1
);
await this.notificationService.inform(Inform.New, informNewPeople, language);
await this.replaceOrAddTrending(language, hash, arr);
}

Comment on lines +120 to +136
test('CT3: Teste com data contendo valores inválidos', async () => {
const data: Array<{ name: string; position: number }> = [
{ name: 'item1', position: Number('string') }, // Garantir que seja número
{ name: 'item2', position: 3 },
];

mockStarsRepository.getTrendingByLanguage.mockResolvedValue({
hash: 'hash1',
trendingList: JSON.stringify([{ name: 'item3', position: 6 }]),
});

await service.updateTrending('en', 'hash2', data);

expect(mockStarsRepository.getTrendingByLanguage).toHaveBeenCalled();
expect(mockNotificationService.inform).not.toHaveBeenCalled();
expect(mockReplaceOrAddTrending).not.toHaveBeenCalled();
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve invalid data test case.

The test case for invalid data should be more explicit about what makes the data invalid and what behavior is expected.

-  test('CT3: Teste com data contendo valores inválidos', async () => {
+  test('should not process updates when position values are invalid numbers', async () => {
     const data: Array<{ name: string; position: number }> = [
-      { name: 'item1', position: Number('string') }, // Garantir que seja número
+      { name: 'item1', position: NaN }, // Invalid position
       { name: 'item2', position: 3 },
     ];
 
     mockStarsRepository.getTrendingByLanguage.mockResolvedValue({
       hash: 'hash1',
       trendingList: JSON.stringify([{ name: 'item3', position: 6 }]),
     });
 
     await service.updateTrending('en', 'hash2', data);
 
     expect(mockStarsRepository.getTrendingByLanguage).toHaveBeenCalled();
-    expect(mockNotificationService.inform).not.toHaveBeenCalled();
-    expect(mockReplaceOrAddTrending).not.toHaveBeenCalled();
+    expect(() => service.updateTrending('en', 'hash2', data)).rejects.toThrow('Invalid position value');
   });

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

@nevo-david
Copy link
Contributor

I am not sure what is this, are you just adding stuff with AI?
Closing for now.

@nevo-david nevo-david closed this Jan 19, 2025
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.

2 participants