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
57 changes: 55 additions & 2 deletions src/reduce.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,62 @@ describe('reduce', () => {
delete Array.prototype.reduce2;
});

it('should ', () => {
let callback;

beforeEach(() => {
callback = jest.fn().mockImplementation((a, b) => a + b);
});

// Add tests here
it('should be declared', () => {
expect(reduce).toBeInstanceOf(Function);
});

it('should not mutate array', () => {
const array = [1, 2, 3, 4];

const copy = [...array];

array.reduce2(callback, 0);

expect(array).toEqual(copy);
});

it('should run callback array`s length times if initialValue is', () => {
const array = [1, 2, 3, 4];

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

expect(callback).toHaveBeenCalledTimes(array.length); ;
expect(result).toBe(10);
});

it('should run callback array`s length - 1 times if no initialValue', () => {
const array = [1, 2, 3, 4];

const result = array.reduce2(callback);

expect(callback).toHaveBeenCalledTimes(array.length - 1); ;
expect(result).toBe(10);
});

it('should run callback with correct arguments', () => {
const array = [1, 2, 3, 4];

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

expect(callback).toHaveBeenNthCalledWith(1, 0, 1, 0, array);
expect(callback).toHaveBeenNthCalledWith(2, 1, 2, 1, array);
expect(callback).toHaveBeenNthCalledWith(3, 3, 3, 2, array);
expect(callback).toHaveBeenNthCalledWith(4, 6, 4, 3, array);

expect(result).toBe(10);
});
Comment on lines +52 to +63

Choose a reason for hiding this comment

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

While it's good to check that the callback is called with the correct arguments, you're missing a check for the most important part of reduce: the final accumulated value that it returns. Consider storing the result of array.reduce2() and adding an assertion for it.


it('should return initial value if array is empty', () => {
const array = [];
const initialValue = 0;
const result = array.reduce2(callback, initialValue);

expect(result).toBe(initialValue); ;
});

Choose a reason for hiding this comment

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

According to the Array.prototype.reduce specification, calling reduce on an empty array without providing an initial value should result in a TypeError. Please add a test case to verify this behavior. You can use Jest's expect(() => ...).toThrow(TypeError) to assert that an error is thrown.

});