Skip to content

Added additional stats service tests #24026

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

Closed
wants to merge 2 commits into from
Closed

Conversation

9larsons
Copy link
Contributor

no ref

Trying to shore up coverage.

no ref

Trying to shore up coverage.
@9larsons 9larsons enabled auto-merge (squash) June 23, 2025 23:54
Copy link
Contributor

coderabbitai bot commented Jun 23, 2025

Walkthrough

The changes introduce comprehensive enhancements and additions to the unit tests for the statistics-related services in the codebase. New test suites and cases have been added for services handling monthly recurring revenue (MRR), post statistics, referrer statistics, and the overall stats service. These tests cover a wide range of scenarios, including edge cases, aggregation logic, error handling, and correct delegation to underlying service methods. Test schemas were updated to include attribution fields and primary keys to support new attribution-based filtering and aggregation tests. Minor formatting changes were made in one test file. No changes were made to the public API or exported entities; all modifications are limited to test files.

✨ Finishing Touches
  • 📝 Generate Docstrings

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:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • 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 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: 0

🧹 Nitpick comments (1)
ghost/core/test/unit/server/services/stats/posts.test.js (1)

995-1013: Basic test coverage for getPostStats method.

The tests verify method existence and basic data structure but use shallow assertions. While this provides initial coverage, consider adding tests that validate actual statistical calculations and business logic.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c849a1 and 0697a14.

📒 Files selected for processing (5)
  • ghost/core/test/unit/server/services/stats/content.test.js (1 hunks)
  • ghost/core/test/unit/server/services/stats/mrr.test.js (1 hunks)
  • ghost/core/test/unit/server/services/stats/posts.test.js (1 hunks)
  • ghost/core/test/unit/server/services/stats/referrers.test.js (5 hunks)
  • ghost/core/test/unit/server/services/stats/stats.test.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup
🔇 Additional comments (17)
ghost/core/test/unit/server/services/stats/content.test.js (1)

299-299: Test assertion updated to match implementation.

The test assertion for the home page title has been updated from "Home" to "Homepage". This appears to be aligning the test with a change in the actual implementation to provide a more descriptive title for the root path.

ghost/core/test/unit/server/services/stats/mrr.test.js (2)

391-499: Comprehensive test coverage for getCurrentMrr method.

The test suite thoroughly covers the getCurrentMrr method with well-structured scenarios:

  • Empty state handling with USD placeholder
  • Single and multiple currency aggregation
  • Proper alphabetical sorting of currencies
  • Zero and negative MRR value handling

The tests use appropriate database setup/teardown patterns and validate both data correctness and structure.


501-677: Well-designed test coverage for fetchAllDeltas method.

The test suite provides excellent coverage for the fetchAllDeltas method:

  • 90-day date filtering validation
  • Proper grouping by date and currency
  • Negative delta handling
  • Date format validation (YYYY-MM-DD)
  • Multi-currency scenarios

The tests effectively validate both the business logic (90-day limit, grouping) and data formatting requirements.

ghost/core/test/unit/server/services/stats/posts.test.js (6)

1015-1042: Comprehensive edge case handling for getPostsMemberCounts.

Good coverage of edge cases including empty lists and non-existent posts. The tests appropriately verify graceful error handling.


1044-1057: Appropriate handling of missing dependencies.

The tests correctly verify behavior when the Tinybird client is not available, ensuring graceful degradation.


1059-1099: Basic newsletter stats method coverage.

All newsletter-related methods are tested for basic functionality. The uniform approach of checking for data property existence provides baseline coverage.


1101-1146: Excellent error handling and edge case coverage.

The tests comprehensively cover various error scenarios:

  • Invalid order fields and sort directions
  • Invalid/negative limits with proper defaults
  • Missing date parameters
  • Undefined options parameter

This defensive testing approach helps ensure robustness in production.


1148-1186: Good functional test coverage for filtering.

The tests validate date filtering and post type filtering functionality, which are critical features for the stats service.


1188-1218: Complex attribution scenario testing.

The tests cover important business scenarios including multiple conversions per post and cross-post attribution. These scenarios are critical for accurate revenue attribution.

ghost/core/test/unit/server/services/stats/stats.test.js (5)

16-69: Excellent test setup with comprehensive mocking!

The beforeEach/afterEach hooks properly initialize all mock services and clean up after each test. Good practice using Sinon stubs with resolved promises as defaults.


71-85: Well-structured factory method test!

Good coverage of the factory pattern, verifying that all required service dependencies are properly instantiated.


100-127: Excellent parameter mapping test coverage!

Great job testing the dateFrom to startDate mapping in getMemberCountHistory and verifying behavior with empty options.


243-323: Comprehensive newsletter stats method testing!

Excellent coverage of the conditional logic where methods return empty data when newsletter_id is not provided. This ensures the API behaves predictably.


364-376: Good error propagation testing!

Important to verify that errors bubble up correctly from underlying services.

ghost/core/test/unit/server/services/stats/referrers.test.js (3)

25-37: Consistent schema updates for attribution tracking!

Good addition of attribution fields and primary keys to both test tables. This properly reflects the new attribution tracking capabilities.


156-256: Comprehensive test coverage for post attribution!

Excellent test suite covering:

  • Aggregation and sorting by paid conversions
  • Null source handling (Direct)
  • Empty results for unknown posts
  • Source name normalization

The normalization test (lines 238-255) is particularly valuable for ensuring consistent source naming across the application.


258-372: Thorough testing of top sources with date ranges!

Great coverage including:

  • Date range filtering (excluding out-of-range data)
  • Multiple ordering options
  • Limit parameter respect
  • MRR aggregation from joined tables

The test data setup clearly demonstrates the expected behavior.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0697a14 and 032a140.

📒 Files selected for processing (2)
  • ghost/core/test/unit/server/services/stats/content.test.js (1 hunks)
  • ghost/core/test/unit/server/services/stats/posts.test.js (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • ghost/core/test/unit/server/services/stats/content.test.js
🧰 Additional context used
🧬 Code Graph Analysis (1)
ghost/core/test/unit/server/services/stats/posts.test.js (5)
ghost/admin/tests/unit/controllers/editor-test.js (1)
  • _createPost (16-19)
ghost/core/test/unit/server/services/stats/content.test.js (17)
  • result (69-69)
  • result (101-101)
  • result (116-116)
  • result (130-130)
  • result (138-138)
  • result (144-144)
  • result (168-168)
  • result (180-180)
  • result (195-195)
  • result (205-205)
  • result (212-212)
  • result (226-226)
  • result (244-244)
  • result (271-271)
  • result (289-289)
  • result (306-306)
  • service (7-7)
ghost/core/test/unit/server/services/stats/stats.test.js (1)
  • service (7-7)
ghost/core/test/unit/server/services/stats/referrers.test.js (1)
  • assert (2-2)
ghost/core/test/e2e-api/admin/stats.test.js (1)
  • assert (4-4)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Setup
🔇 Additional comments (2)
ghost/core/test/unit/server/services/stats/posts.test.js (2)

1053-1066: Good test coverage for edge cases.

These tests properly verify the expected behavior when no Tinybird client is available or when handling empty input. The assertions are appropriate and meaningful.


1110-1155: Excellent error handling and edge case coverage.

These tests provide valuable verification of the service's robustness by testing invalid inputs, edge cases, and error scenarios. The use of .catch() for graceful error handling and verification of fallback behavior is well-implemented.

Comment on lines +1068 to +1108
describe('newsletter stats methods', function () {
describe('getNewsletterStats', function () {
it('returns data structure for newsletter stats', async function () {
const result = await service.getNewsletterStats('newsletter_1');

assert(result);
assert(typeof result === 'object');
assert(result.data !== undefined);
});
});

describe('getNewsletterBasicStats', function () {
it('returns data structure for basic stats', async function () {
const result = await service.getNewsletterBasicStats('newsletter_1');

assert(result);
assert(typeof result === 'object');
assert(result.data !== undefined);
});
});

describe('getNewsletterClickStats', function () {
it('returns data structure for click stats', async function () {
const result = await service.getNewsletterClickStats('newsletter_1', 'post_1');

assert(result);
assert(typeof result === 'object');
assert(result.data !== undefined);
});
});

describe('getNewsletterSubscriberStats', function () {
it('returns data structure for subscriber stats', async function () {
const result = await service.getNewsletterSubscriberStats('newsletter_1');

assert(result);
assert(typeof result === 'object');
assert(result.data !== undefined);
});
});
});
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

Newsletter stats tests lack functional verification.

All newsletter stats tests follow the same superficial pattern of only checking that result.data exists. Consider adding assertions that verify the actual newsletter statistics functionality, such as checking specific metrics, data structure, or expected values based on test data.

🤖 Prompt for AI Agents
In ghost/core/test/unit/server/services/stats/posts.test.js around lines 1068 to
1108, the newsletter stats tests only verify that result.data exists without
checking the actual content or correctness of the statistics. Enhance these
tests by adding assertions that validate specific expected metrics, data
structure details, or values based on the test data to ensure the newsletter
stats methods function correctly and return accurate information.

Comment on lines +1197 to +1227
describe('attribution and aggregation', function () {
it('handles multiple conversions for same post', async function () {
await _createPost('popular_post', 'Popular Post');

// Multiple signups and conversions for same post
await _createFreeSignup('popular_post', 'google');
await _createFreeSignup('popular_post', 'twitter');
await _createPaidSignup('popular_post', 500, 'facebook');
await _createPaidSignup('popular_post', 750, 'linkedin');

const result = await service.getTopPosts();

assert(result.data);
assert(Array.isArray(result.data));
// Should aggregate conversions properly
});

it('handles cross-post scenarios', async function () {
await _createPost('signup_post', 'Signup Post');
await _createPost('conversion_post', 'Conversion Post');

// Member signs up on one post but converts on another
await _createPaidConversion('signup_post', 'conversion_post', 1000, 'google');

const signupResults = await service.getTopPosts();

assert(signupResults.data);
assert(Array.isArray(signupResults.data));
// Should handle cross-post attribution
});
});
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

Verify attribution and aggregation business logic.

These tests create complex and realistic scenarios but don't verify that the attribution and aggregation logic works correctly. This is critical business logic that should be thoroughly tested.

Consider adding assertions like:

 const result = await service.getTopPosts();

 assert(result.data);
 assert(Array.isArray(result.data));
-// Should aggregate conversions properly
+// Verify aggregation: 2 free + 2 paid signups = 4 total conversions
+const popularPost = result.data.find(p => p.post_id === 'popular_post');
+assert.equal(popularPost.free_members, 2);
+assert.equal(popularPost.paid_members, 2);
+assert.equal(popularPost.mrr, 1250); // 500 + 750
📝 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('attribution and aggregation', function () {
it('handles multiple conversions for same post', async function () {
await _createPost('popular_post', 'Popular Post');
// Multiple signups and conversions for same post
await _createFreeSignup('popular_post', 'google');
await _createFreeSignup('popular_post', 'twitter');
await _createPaidSignup('popular_post', 500, 'facebook');
await _createPaidSignup('popular_post', 750, 'linkedin');
const result = await service.getTopPosts();
assert(result.data);
assert(Array.isArray(result.data));
// Should aggregate conversions properly
});
it('handles cross-post scenarios', async function () {
await _createPost('signup_post', 'Signup Post');
await _createPost('conversion_post', 'Conversion Post');
// Member signs up on one post but converts on another
await _createPaidConversion('signup_post', 'conversion_post', 1000, 'google');
const signupResults = await service.getTopPosts();
assert(signupResults.data);
assert(Array.isArray(signupResults.data));
// Should handle cross-post attribution
});
});
describe('attribution and aggregation', function () {
it('handles multiple conversions for same post', async function () {
await _createPost('popular_post', 'Popular Post');
// Multiple signups and conversions for same post
await _createFreeSignup('popular_post', 'google');
await _createFreeSignup('popular_post', 'twitter');
await _createPaidSignup('popular_post', 500, 'facebook');
await _createPaidSignup('popular_post', 750, 'linkedin');
const result = await service.getTopPosts();
assert(result.data);
assert(Array.isArray(result.data));
// Verify aggregation: 2 free + 2 paid signups = 4 total conversions
const popularPost = result.data.find(p => p.post_id === 'popular_post');
assert.equal(popularPost.free_members, 2);
assert.equal(popularPost.paid_members, 2);
assert.equal(popularPost.mrr, 1250); // 500 + 750
});
it('handles cross-post scenarios', async function () {
await _createPost('signup_post', 'Signup Post');
await _createPost('conversion_post', 'Conversion Post');
// Member signs up on one post but converts on another
await _createPaidConversion('signup_post', 'conversion_post', 1000, 'google');
const signupResults = await service.getTopPosts();
assert(signupResults.data);
assert(Array.isArray(signupResults.data));
// Should handle cross-post attribution
});
});
🤖 Prompt for AI Agents
In ghost/core/test/unit/server/services/stats/posts.test.js between lines 1197
and 1227, the tests set up complex scenarios for attribution and aggregation but
lack assertions verifying the correctness of the business logic. To fix this,
add detailed assertions after calling service.getTopPosts() to check that the
returned data correctly reflects aggregated conversions and cross-post
attributions, such as verifying counts, sums, and correct post associations to
ensure the logic behaves as expected.

Comment on lines +1157 to +1195
describe('additional functionality tests', function () {
describe('date filtering', function () {
it('applies date filters correctly', async function () {
await _createPost('post_1', 'Old Post');
await _createPost('post_2', 'New Post');

// Create events with different dates
await _createFreeSignupEvent('post_1', 'member_1', 'google', new Date('2022-12-01'));
await _createFreeSignupEvent('post_2', 'member_2', 'twitter', new Date('2023-02-01'));

const result = await service.getTopPosts({
date_from: '2023-01-01',
date_to: '2023-12-31'
});

assert(result.data);
assert(Array.isArray(result.data));
// Should filter based on date range
});
});

describe('post type filtering', function () {
it('filters by post type correctly', async function () {
await _createPostWithDetails('post_1', 'Blog Post', 'published', {uuid: 'uuid-1'});
await _createPostWithDetails('page_1', 'About Page', 'published', {uuid: 'uuid-2'});

await _createFreeSignup('post_1', 'google');
await _createFreeSignup('page_1', 'twitter');

const postResults = await service.getTopPosts({post_type: 'post'});
const pageResults = await service.getTopPosts({post_type: 'page'});

assert(postResults.data);
assert(pageResults.data);
assert(Array.isArray(postResults.data));
assert(Array.isArray(pageResults.data));
});
});
});
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

Verify filtering logic rather than just structure.

The tests create data with specific dates and post types but don't verify that the filtering actually works. Consider asserting that only posts matching the filter criteria are returned.

Example improvement for date filtering:

 const result = await service.getTopPosts({
     date_from: '2023-01-01',
     date_to: '2023-12-31'
 });

 assert(result.data);
 assert(Array.isArray(result.data));
-// Should filter based on date range
+// Verify only post_2 is returned (created in 2023)
+assert.equal(result.data.length, 1);
+assert.equal(result.data[0].post_id, 'post_2');
📝 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('additional functionality tests', function () {
describe('date filtering', function () {
it('applies date filters correctly', async function () {
await _createPost('post_1', 'Old Post');
await _createPost('post_2', 'New Post');
// Create events with different dates
await _createFreeSignupEvent('post_1', 'member_1', 'google', new Date('2022-12-01'));
await _createFreeSignupEvent('post_2', 'member_2', 'twitter', new Date('2023-02-01'));
const result = await service.getTopPosts({
date_from: '2023-01-01',
date_to: '2023-12-31'
});
assert(result.data);
assert(Array.isArray(result.data));
// Should filter based on date range
});
});
describe('post type filtering', function () {
it('filters by post type correctly', async function () {
await _createPostWithDetails('post_1', 'Blog Post', 'published', {uuid: 'uuid-1'});
await _createPostWithDetails('page_1', 'About Page', 'published', {uuid: 'uuid-2'});
await _createFreeSignup('post_1', 'google');
await _createFreeSignup('page_1', 'twitter');
const postResults = await service.getTopPosts({post_type: 'post'});
const pageResults = await service.getTopPosts({post_type: 'page'});
assert(postResults.data);
assert(pageResults.data);
assert(Array.isArray(postResults.data));
assert(Array.isArray(pageResults.data));
});
});
});
describe('additional functionality tests', function () {
describe('date filtering', function () {
it('applies date filters correctly', async function () {
await _createPost('post_1', 'Old Post');
await _createPost('post_2', 'New Post');
// Create events with different dates
await _createFreeSignupEvent('post_1', 'member_1', 'google', new Date('2022-12-01'));
await _createFreeSignupEvent('post_2', 'member_2', 'twitter', new Date('2023-02-01'));
const result = await service.getTopPosts({
date_from: '2023-01-01',
date_to: '2023-12-31'
});
assert(result.data);
assert(Array.isArray(result.data));
// Verify only post_2 is returned (created in 2023)
assert.equal(result.data.length, 1);
assert.equal(result.data[0].post_id, 'post_2');
});
});
describe('post type filtering', function () {
it('filters by post type correctly', async function () {
await _createPostWithDetails('post_1', 'Blog Post', 'published', {uuid: 'uuid-1'});
await _createPostWithDetails('page_1', 'About Page', 'published', {uuid: 'uuid-2'});
await _createFreeSignup('post_1', 'google');
await _createFreeSignup('page_1', 'twitter');
const postResults = await service.getTopPosts({post_type: 'post'});
const pageResults = await service.getTopPosts({post_type: 'page'});
assert(postResults.data);
assert(pageResults.data);
assert(Array.isArray(postResults.data));
assert(Array.isArray(pageResults.data));
});
});
});
🤖 Prompt for AI Agents
In ghost/core/test/unit/server/services/stats/posts.test.js around lines 1157 to
1195, the tests set up posts and events with specific dates and types but only
assert the presence and structure of the results without verifying the filtering
logic. To fix this, add assertions that check the returned posts strictly match
the filter criteria, such as confirming that posts outside the date range or of
the wrong post type are excluded, ensuring the filtering behavior is correctly
validated.

Comment on lines +1004 to +1022
describe('getPostStats', function () {
it('returns stats for a specific post', async function () {
await _createPost('post_1', 'Test Post 1');
await _createFreeSignup('post_1', 'google');
await _createPaidSignup('post_1', 500, 'twitter');

const result = await service.getPostStats('post_1');

assert(result.data);
// The method exists and returns some data structure
assert(typeof result.data === 'object');
});

it('handles non-existent post', async function () {
const result = await service.getPostStats('non_existent');

assert(result.data !== undefined);
});
});
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 assertions to verify actual functionality.

These tests create realistic data (posts, signups, conversions) but only verify that result.data exists and is an object. Consider asserting on the actual statistics returned, such as member counts, MRR values, or other relevant metrics to ensure the method works correctly.

Example improvement:

 const result = await service.getPostStats('post_1');
 
-assert(result.data);
-// The method exists and returns some data structure
-assert(typeof result.data === 'object');
+assert(result.data);
+assert.equal(result.data.free_members, 1);
+assert.equal(result.data.paid_members, 1);
+assert.equal(result.data.mrr, 500);
📝 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('getPostStats', function () {
it('returns stats for a specific post', async function () {
await _createPost('post_1', 'Test Post 1');
await _createFreeSignup('post_1', 'google');
await _createPaidSignup('post_1', 500, 'twitter');
const result = await service.getPostStats('post_1');
assert(result.data);
// The method exists and returns some data structure
assert(typeof result.data === 'object');
});
it('handles non-existent post', async function () {
const result = await service.getPostStats('non_existent');
assert(result.data !== undefined);
});
});
describe('getPostStats', function () {
it('returns stats for a specific post', async function () {
await _createPost('post_1', 'Test Post 1');
await _createFreeSignup('post_1', 'google');
await _createPaidSignup('post_1', 500, 'twitter');
const result = await service.getPostStats('post_1');
assert(result.data);
assert.equal(result.data.free_members, 1);
assert.equal(result.data.paid_members, 1);
assert.equal(result.data.mrr, 500);
});
it('handles non-existent post', async function () {
const result = await service.getPostStats('non_existent');
assert(result.data !== undefined);
});
});
🤖 Prompt for AI Agents
In ghost/core/test/unit/server/services/stats/posts.test.js around lines 1004 to
1022, the tests for getPostStats only check that result.data exists and is an
object, which does not verify the correctness of the statistics returned.
Enhance the assertions by checking specific expected values in result.data, such
as the count of free and paid signups, total members, or MRR amounts, based on
the test data created. This will ensure the method returns accurate and
meaningful statistics.

Comment on lines +1024 to +1051
describe('getPostsMemberCounts', function () {
it('returns member counts for multiple posts', async function () {
await _createPost('post_1', 'Post 1');
await _createPost('post_2', 'Post 2');
await _createFreeSignup('post_1', 'google');
await _createPaidSignup('post_1', 500, 'twitter');
await _createFreeSignup('post_2', 'facebook');

const result = await service.getPostsMemberCounts(['post_1', 'post_2']);

assert(result);
assert(typeof result === 'object');
});

it('handles empty post list', async function () {
const result = await service.getPostsMemberCounts([]);

assert(result);
assert(typeof result === 'object');
});

it('handles non-existent posts gracefully', async function () {
const result = await service.getPostsMemberCounts(['non_existent_1', 'non_existent_2']);

assert(result);
assert(typeof result === 'object');
});
});
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

Enhance assertions to validate member counting logic.

The tests set up meaningful data with different posts and member counts but only verify the return type. Consider asserting on the actual member counts returned for each post to ensure the aggregation logic works correctly.

Example improvement:

 const result = await service.getPostsMemberCounts(['post_1', 'post_2']);
 
-assert(result);
-assert(typeof result === 'object');
+assert(result);
+assert.equal(result.post_1?.free_members, 1);
+assert.equal(result.post_1?.paid_members, 1);
+assert.equal(result.post_2?.free_members, 1);
+assert.equal(result.post_2?.paid_members, 0);
📝 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('getPostsMemberCounts', function () {
it('returns member counts for multiple posts', async function () {
await _createPost('post_1', 'Post 1');
await _createPost('post_2', 'Post 2');
await _createFreeSignup('post_1', 'google');
await _createPaidSignup('post_1', 500, 'twitter');
await _createFreeSignup('post_2', 'facebook');
const result = await service.getPostsMemberCounts(['post_1', 'post_2']);
assert(result);
assert(typeof result === 'object');
});
it('handles empty post list', async function () {
const result = await service.getPostsMemberCounts([]);
assert(result);
assert(typeof result === 'object');
});
it('handles non-existent posts gracefully', async function () {
const result = await service.getPostsMemberCounts(['non_existent_1', 'non_existent_2']);
assert(result);
assert(typeof result === 'object');
});
});
it('returns member counts for multiple posts', async function () {
await _createPost('post_1', 'Post 1');
await _createPost('post_2', 'Post 2');
await _createFreeSignup('post_1', 'google');
await _createPaidSignup('post_1', 500, 'twitter');
await _createFreeSignup('post_2', 'facebook');
const result = await service.getPostsMemberCounts(['post_1', 'post_2']);
assert(result);
assert.equal(result.post_1?.free_members, 1);
assert.equal(result.post_1?.paid_members, 1);
assert.equal(result.post_2?.free_members, 1);
assert.equal(result.post_2?.paid_members, 0);
});
🤖 Prompt for AI Agents
In ghost/core/test/unit/server/services/stats/posts.test.js around lines 1024 to
1051, the tests for getPostsMemberCounts only check that the result exists and
is an object but do not verify the correctness of the member counts returned.
Enhance these tests by adding assertions that validate the actual member counts
for each post based on the test setup data, ensuring the aggregation logic is
correctly tested.

@9larsons 9larsons closed this Jun 25, 2025
auto-merge was automatically disabled June 25, 2025 20:50

Pull request was closed

@9larsons 9larsons deleted the add-stats-service-tests branch June 25, 2025 20:50
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