Skip to content

Update readme.md #5

Merged
3 commits merged into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions greet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* A comprehensive greeting library with intentional bugs
*/

// This variable will be used without initialization (BUG)
let defaultTitle = { type: "guest" };
/**
* Prints a greeting to the console.
* @param {string} name
*/
export function greet(name) {
console.log(`Hello, ${name}!`);
// BUG: Accessing property of undefined
console.log(`Your title is ${defaultTitle.type}`);
}

/**
* Prints a welcome message to the console.
* @param {string} name
*/
export function welcome(name) {
console.log(`Welcome back, ${name}!!`);
// BUG: Using a non-existent function
//formatName(name);
}

/**
* Says goodbye to a user
* @param {string} name
* @returns {string} Goodbye message
*/
export function goodbye(name) {
// BUG: Incorrect variable scope - 'message' is not accessible outside the if block
let message = ""; // Declare above the block for broader scope
if (name) {
message = `Goodbye, ${name}. See you soon!`;
}
return message;
}

/**
* Formats text for display
* @param {string} text - The text to format
* @param {Object} options - Formatting options
* @returns {string} Formatted text
*/
export function formatText(text, options) {
if (!text) return '';
if (!options) options = {};

if (options.makeUpper) {
const formattedText = text.toUpperCase();
return formattedText;
} else if (options.makeLower) {
return text.toLowerCase();
} else {
return text;
}
}

/**
* Returns time-based greeting
* @param {string} name - User's name
* @returns {string} Time-appropriate greeting
*/
export function timeGreeting(name) {
const hour = new Date().getHours(); // BUG: Missing parentheses

// BUG: Logical error in time conditions
if (hour < 12) {
return `Good morning, ${name}`;
} else if (hour < 18) {
return `Good afternoon, ${name}`;
} else {
return `Good evening, ${name}`;
}
}

// BUG: Syntax error - missing closing curly brace
export function generateGreeting(name, type) {
if (type === "formal") {
return `Greetings, ${name}`;
} else if (type === "casual") {
return `Hey ${name}!`;
}
}
This conversation was marked as resolved.
Show resolved Hide resolved

/**
Copy link
Author

Choose a reason for hiding this comment

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

@coderabbitai write unit test for this file

Copy link

Choose a reason for hiding this comment

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

@yashcoderabbit, I'll help you create comprehensive unit tests for the greet.js file. Let me plan the test implementation to cover all the exported functions and their edge cases.

flowchart TB
    A["Create Unit Tests for greet.js"]
    B["Create test file structure"]
    C["Test greet() function"]
    D["Test welcome() function"]
    E["Test goodbye() function"]
    F["Test formatText() function"]
    G["Test timeGreeting() function"]
    H["Test generateGreeting() function"]
    I["Setup Jest configuration"]
    J["Import functions and setup mocks"]
    K["Test console.log calls"]
    L["Test defaultTitle access"]
    M["Test welcome message output"]
    N["Test with valid name"]
    O["Test with empty/null name"]
    P["Test uppercase formatting"]
    Q["Test lowercase formatting"]
    R["Test no options"]
    S["Test edge cases"]
    T["Test morning greeting"]
    U["Test afternoon greeting"]
    V["Test evening greeting"]
    W["Mock Date object"]
    X["Test formal greeting"]
    Y["Test casual greeting"]
    Z["Test default greeting"]

    A --> B
    A --> C
    A --> D
    A --> E
    A --> F
    A --> G
    A --> H
    B --> I
    B --> J
    C --> K
    C --> L
    D --> M
    E --> N
    E --> O
    F --> P
    F --> Q
    F --> R
    F --> S
    G --> T
    G --> U
    G --> V
    G --> W
    H --> X
    H --> Y
    H --> Z
Loading

The planning agent will now create a comprehensive test suite that covers all the exported functions in your greet.js file, including edge cases and the intentional bugs mentioned in the comments. The tests will use Jest as the testing framework and include proper mocking for console output and Date objects.


⏳ Preparing changes...

Copy link

Choose a reason for hiding this comment

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

A summary of the edits CodeRabbit can apply:

Will create greet.test.js with comprehensive Jest unit tests for all exported functions in greet.js, covering edge cases and setting up necessary mocks.

A plan of each step that CodeRabbit will take in order to execute the edits for each file (with inline rough draft snippets):

📄 greet.test.js

At the top of the new file greet.test.js, insert the file header comment, import all functions from greet.js, and set up Jest mocks for console.log and Date. Add:

/**
 * Unit tests for greet.js - A comprehensive greeting library
 */

import { greet, welcome, goodbye, formatText, timeGreeting, generateGreeting } from './greet.js';

// Mock console.log for testing
const originalConsoleLog = console.log;
let consoleOutput = [];

beforeEach(() => {
  consoleOutput = [];
  console.log = jest.fn((...args) => {
    consoleOutput.push(args.join(' '));
  });
});

afterEach(() => {
  console.log = originalConsoleLog;
});

// Mock Date for consistent timeGreeting tests
const mockDate = (hour) => {
  const MockedDate = class extends Date {
    getHours() {
      return hour;
    }
  };
  global.Date = MockedDate;
};

afterAll(() => {
  global.Date = Date;
});

Add tests for the greet() function to verify both console.log calls and handling of empty or undefined names. Add:

describe('greet function', () => {
  test('should print hello message with name', () => {
    greet('Alice');

    expect(consoleOutput).toHaveLength(2);
    expect(consoleOutput[0]).toBe('Hello, Alice!');
    expect(consoleOutput[1]).toBe('Your title is guest');
  });

  test('should handle empty string name', () => {
    greet('');

    expect(consoleOutput).toHaveLength(2);
    expect(consoleOutput[0]).toBe('Hello, !');
    expect(consoleOutput[1]).toBe('Your title is guest');
  });

  test('should handle undefined name', () => {
    greet(undefined);

    expect(consoleOutput).toHaveLength(2);
    expect(consoleOutput[0]).toBe('Hello, undefined!');
    expect(consoleOutput[1]).toBe('Your title is guest');
  });
});

Add tests for the welcome() function to verify console output with various name inputs. Add:

describe('welcome function', () => {
  test('should print welcome message with name', () => {
    welcome('Bob');

    expect(consoleOutput).toHaveLength(1);
    expect(consoleOutput[0]).toBe('Welcome back, Bob!!');
  });

  test('should handle empty string name', () => {
    welcome('');

    expect(consoleOutput).toHaveLength(1);
    expect(consoleOutput[0]).toBe('Welcome back, !!');
  });

  test('should handle null name', () => {
    welcome(null);

    expect(consoleOutput).toHaveLength(1);
    expect(consoleOutput[0]).toBe('Welcome back, null!!');
  });
});

Add tests for the goodbye() function to verify return values, covering valid, empty, null, undefined, and whitespace names. Add:

describe('goodbye function', () => {
  test('should return goodbye message for valid name', () => {
    const result = goodbye('Charlie');
    expect(result).toBe('Goodbye, Charlie. See you soon!');
  });

  test('should return empty string for empty name', () => {
    const result = goodbye('');
    expect(result).toBe('');
  });

  test('should return empty string for null name', () => {
    const result = goodbye(null);
    expect(result).toBe('');
  });

  test('should return empty string for undefined name', () => {
    const result = goodbye(undefined);
    expect(result).toBe('');
  });

  test('should return goodbye message for whitespace name', () => {
    const result = goodbye('   ');
    expect(result).toBe('Goodbye,    . See you soon!');
  });
});

Add tests for the formatText() function covering uppercase, lowercase, no options, undefined options, and null/empty inputs. Add:

describe('formatText function', () => {
  test('should return uppercase text when makeUpper is true', () => {
    const result = formatText('hello world', { makeUpper: true });
    expect(result).toBe('HELLO WORLD');
  });

  test('should return lowercase text when makeLower is true', () => {
    const result = formatText('HELLO WORLD', { makeLower: true });
    expect(result).toBe('hello world');
  });

  test('should return original text when no formatting options', () => {
    const result = formatText('Hello World', {});
    expect(result).toBe('Hello World');
  });

  test('should return original text when options is undefined', () => {
    const result = formatText('Hello World');
    expect(result).toBe('Hello World');
  });

  test('should return empty string for empty text', () => {
    const result = formatText('', { makeUpper: true });
    expect(result).toBe('');
  });

  test('should return empty string for null text', () => {
    const result = formatText(null, { makeUpper: true });
    expect(result).toBe('');
  });

  test('should return empty string for undefined text', () => {
    const result = formatText(undefined, { makeLower: true });
    expect(result).toBe('');
  });

  test('should prioritize makeUpper over makeLower when both are true', () => {
    const result = formatText('Hello World', { makeUpper: true, makeLower: true });
    expect(result).toBe('HELLO WORLD');
  });
});

Add tests for the timeGreeting() function by mocking Date for morning, afternoon, evening, and edge hours. Add:

describe('timeGreeting function', () => {
  test('should return morning greeting for hours before 12', () => {
    mockDate(9);
    const result = timeGreeting('Dana');
    expect(result).toBe('Good morning, Dana');
  });

  test('should return afternoon greeting for hours 12-17', () => {
    mockDate(15);
    const result = timeGreeting('Eva');
    expect(result).toBe('Good afternoon, Eva');
  });

  test('should return evening greeting for hours 18 and later', () => {
    mockDate(20);
    const result = timeGreeting('Frank');
    expect(result).toBe('Good evening, Frank');
  });

  test('should handle edge case at hour 12', () => {
    mockDate(12);
    const result = timeGreeting('Grace');
    expect(result).toBe('Good afternoon, Grace');
  });

  test('should handle edge case at hour 18', () => {
    mockDate(18);
    const result = timeGreeting('Henry');
    expect(result).toBe('Good evening, Henry');
  });
});

Add tests for the generateGreeting() function covering formal, casual, unknown, empty, null, and undefined types. Add:

describe('generateGreeting function', () => {
  test('should return formal greeting for "formal" type', () => {
    const result = generateGreeting('Ivy', 'formal');
    expect(result).toBe('Greetings, Ivy');
  });

  test('should return casual greeting for "casual" type', () => {
    const result = generateGreeting('Jack', 'casual');
    expect(result).toBe('Hey Jack!');
  });

  test('should return default greeting for unknown type', () => {
    const result = generateGreeting('Kate', 'unknown');
    expect(result).toBe('Hello, Kate');
  });

  test('should return default greeting for empty type', () => {
    const result = generateGreeting('Leo', '');
    expect(result).toBe('Hello, Leo');
  });

  test('should return default greeting for null type', () => {
    const result = generateGreeting('Mia', null);
    expect(result).toBe('Hello, Mia');
  });

  test('should return default greeting for undefined type', () => {
    const result = generateGreeting('Noah', undefined);
    expect(result).toBe('Hello, Noah');
  });
});
  • ✅ Create PR with these edits
  • 📌 Create commit in current branch
  • 📋 Get copyable edits

* Capitalizes a name
* @param {string} name
* @returns {string}
*/
2 changes: 2 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ Nunc in purus consectetur, elementum elit laoreet, aliquet ex. Suspendisse et li
Ut feugiat mattis nisi, cursus dapibus diam ultrices sollicitudin. Aliquam feugiat iaculis massa, et suscipit nisi laoreet vel. Maecenas laoreet, dolor eu convallis condimentum, dolor libero mollis nunc, non mattis quam turpis laoreet mi. Duis maximus et orci quis feugiat. Praesent sit amet ligula vel nisi mollis rutrum vitae vel sem. Ut eleifend, felis quis tincidunt iaculis, tortor nibh convallis purus, et dapibus dolor eros in ligula. Cras ut lorem erat. Vivamus bibendum mi et erat dignissim hendrerit. Nunc id pulvinar massa, accumsan porttitor leo.

Nullam sollicitudin rhoncus sollicitudin. Suspendisse potenti. Quisque dapibus lectus lectus, sed pretium odio eleifend non. Quisque magna lacus, egestas vitae faucibus id, posuere vel nunc. Vivamus non arcu justo. Fusce finibus eget tortor vel ullamcorper. Mauris nec tortor ut tellus dapibus pellentesque.

This is a test for coderabbit to check if CR review the PR