Skip to content
Open
Changes from all 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
67 changes: 65 additions & 2 deletions src/reduce.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,70 @@ describe('reduce', () => {
delete Array.prototype.reduce2;
});

it('should ', () => {});
it('should be declared', () => {
expect(Array.prototype.reduce2).toBeInstanceOf(Function);
});

it('should sum array with initial value', () => {
const array = [1, 2, 3, 4, 5, 6];
const callback = jest.fn((prev, x) => prev + x);

const result = array.reduce2(callback, 0);

expect(result).toBe(21);
expect(callback).toHaveBeenCalledTimes(6);
});

it('should sum array without initial value', () => {
const array = [1, 2, 3, 4, 5, 6];
const callback = jest.fn((prev, x) => prev + x);

const result = array.reduce2(callback);

expect(result).toBe(21);
expect(callback).toHaveBeenCalledTimes(5);
});

it('should return initial value for empty array', () => {
const array = [];

const callback = jest.fn((prev, x) => prev + x);

const result = array.reduce2(callback, 0);

expect(result).toBe(0);
expect(callback).not.toHaveBeenCalled();
});

// Add tests here
it('should return undefined for empty array without initial value', () => {
const array = [];

const callback = jest.fn((prev, x) => prev + x);

const result = () => array.reduce(callback);

expect(result).toThrow();
});
Comment on lines +49 to +57
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This test case has a few issues that need to be addressed:

  1. Incorrect Function Call: You are testing the native array.reduce() method here, not your custom array.reduce2(). The test should validate your own implementation.
  2. Inaccurate Test Description: The title states it should return undefined, but according to the reduce specification, calling it on an empty array without an initial value must throw a TypeError.
  3. Imprecise Assertion: The assertion should be more specific. Instead of .toThrow(), please check for the exact error type: .toThrow(TypeError).


it('should work with single element and initial value', () => {
const array = [1];

const callback = jest.fn((prev, x) => prev + x);

const result = array.reduce2(callback, 2);

expect(result).toBe(3);
expect(callback).toHaveBeenCalledTimes(1);
});

it('should return element if single element and no initial value', () => {
const array = [1];

const callback = jest.fn((prev, x) => prev + x);

const result = array.reduce2(callback);

expect(result).toBe(1);
expect(callback).not.toHaveBeenCalled();
});
});
Loading