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

feat/be/settings service tests #1001

Merged
merged 3 commits into from
Oct 22, 2024
Merged

Conversation

ajhollid
Copy link
Collaborator

This PR adds tests for the SettingsService

  • Refactor SettingsService to inject dependency
  • Removed a redundant settings check
  • Added tests for SettingsService

Copy link

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes in this pull request focus on the integration of a new SettingsService and the AppSettings model within the Server/index.js file. Key modifications include updating import statements, initializing settingsService with AppSettings, enhancing middleware to include the settings service, and adjusting the order of service creation. The SettingsService class in Server/service/settingsService.js has been modified to accept appSettings as a constructor parameter, enhancing its flexibility. Additionally, a new test suite for SettingsService has been introduced in Server/tests/services/settingsService.test.js.

Changes

File Change Summary
Server/index.js - Added imports for SettingsService and AppSettings.
- Updated settingsService initialization to accept AppSettings.
- Enhanced middleware to include settingsService.
- Adjusted service creation order.
Server/service/settingsService.js - Updated constructor to accept appSettings.
- Modified loadSettings to use this.appSettings.findOne().
- Streamlined error handling in loadSettings.
Server/tests/services/settingsService.test.js - Introduced unit tests for SettingsService, covering constructor, loadSettings, reloadSettings, and getSettings functionalities, with a focus on error handling and settings merging.

Possibly related PRs

Suggested reviewers

  • marcelluscaio
  • jennifer-gan

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:

‼️ 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 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 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.

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: 4

🧹 Outside diff range and nitpick comments (2)
Server/service/settingsService.js (1)

43-43: Yo, this loadSettings method is spittin' hot fire! 🎤🔥

Man, you're droppin' bars with this this.appSettings.findOne() change! It's smoother than Slim Shady's flow. But hey, let's make this error handling even more lit:

Consider tweaking the error handling like this, fam:

- if (!this.settings) {
-   throw new Error("Settings not found");
- }
+ if (!dbSettings) {
+   throw new Error("Settings not found in the database");
+ }

This way, we're catchin' the real issue if the database comes up empty. It's like adding that perfect beat drop to your track, you feel me?

Server/tests/services/settingsService.test.js (1)

87-87: Eliminate stray console.log to keep output clean

The console.log(error); statement in your catch block might be a leftover from debugging. Removing it will prevent unintentional logging during test runs.

Apply this diff to remove the debug statement:

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 02dc186 and 26f38f7.

📒 Files selected for processing (3)
  • Server/index.js (2 hunks)
  • Server/service/settingsService.js (2 hunks)
  • Server/tests/services/settingsService.test.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
Server/service/settingsService.js (1)

32-33: Yo, this constructor change is fire! 🔥

Bro, you just dropped some serious heat with this dependency injection. It's like you're the Eminem of code refactoring! This change is gonna make our testing game stronger than mom's spaghetti.

Server/index.js (1)

37-40: Keep your imports steady

Great job importing SettingsService and AppSettings. Everything's in place and ready to go, no sweat here.

@@ -142,7 +144,7 @@ const startApp = async () => {

// Create services
await connectDbAndRunServer(app, db);
const settingsService = new SettingsService();
const settingsService = new SettingsService(AppSettings);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Don't lose yourself in the initialization order

It looks like settingsService is being instantiated after it's being attached to the request object in the middleware. Let's make sure we've got our services set up before we serve them, so we don't get caught off guard.

Apply this diff to adjust the initialization order:

--- a/Server/index.js
+++ b/Server/index.js
@@ -78,6 +78,14 @@ const startApp = async () => {
     	req.emailService = emailService;
     	req.settingsService = settingsService;
     	next();
     });

+    // Initialize services after middleware
+    const settingsService = new SettingsService(AppSettings);
+    await settingsService.loadSettings();
+    const emailService = new EmailService(
+    	settingsService,
+    	fs,
+    	path,
+    	compile,
+    	mjml2html,
+    	nodemailer,
+    	logger
+    );
     const networkService = new NetworkService(db, emailService, axios, ping, logger, http);
     const jobQueue = await JobQueue.createJobQueue(db, networkService, settingsService);

Committable suggestion was skipped due to low confidence.

Comment on lines +35 to +36
sandbox.restore();
sinon.restore();
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Clean up redundant sinon.restore() to keep our tests steady

In the afterEach function, calling both sandbox.restore(); and sinon.restore(); may be unnecessary. Since we're using the sandbox to stub and mock methods, sandbox.restore(); will handle all restorations. Removing sinon.restore(); can prevent redundancy and keep our tests lean.

Apply this diff to remove the redundant call:

Committable suggestion was skipped due to low confidence.

Comment on lines +29 to +32
mockAppSettings = {
settingOne: 123,
settingTwo: 456,
};
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Initialize mockAppSettings in beforeEach to avoid heavy side effects

Assigning mockAppSettings inside the beforeEach block ensures it's reset before each test, preventing unintended interactions between tests.

Move the initialization into beforeEach:

...

Committable suggestion was skipped due to low confidence.

Comment on lines +127 to +132
try {
settingsService.getSettings();
} catch (error) {
expect(error.message).to.equal("Settings have not been loaded");
}
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Streamline error testing to capture the moment

You can simplify your error assertion by using Chai's expect(...).to.throw() syntax, making your test more concise and readable.

Refactor the test as follows:

Applying this change seizes the opportunity to make your tests cleaner.

Committable suggestion was skipped due to low confidence.

@ajhollid ajhollid merged commit d29fcfb into develop Oct 22, 2024
3 checks passed
@ajhollid ajhollid deleted the feat/be/settings-service-tests branch October 22, 2024 02:12
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