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

fix error on reduce and reduceRight doc #667

Closed
wants to merge 1 commit into from

Conversation

junpos
Copy link

@junpos junpos commented Nov 9, 2016

  1. on first iteration amount is undefined which results in NaN for total.
it('reduce', function () {
  const total = wrapper.find(Bar).reduce((amount, n) => {
    console.log(amount, n.prop('amount'));
    return amount + n.prop('amount');
  });
  expect(total).to.equal(16);
});
AssertionError: expected NaN to equal 16
  + expected - actual

    -NaN
    +16

// log
undefined 2
NaN 4
NaN 8

It needs a sanity check whether amount is defined, or have an initial value.

wrapper.find(Bar).reduce((acc, n) => {
  const amount = n.prop('amount');
  return acc 
    ? acc + amount
    : amount;
});
//or
wrapper.find(Bar).reduce((amount, n) => amount + n.prop('amount'), 0);
  1. And the total should be 14 instead of 16

@@ -41,8 +41,8 @@ class Foo extends React.Component {

```jsx
const wrapper = mount(<Foo />);
const total = wrapper.find(Bar).reduce((amount, n) => amount + n.prop('amount'));
expect(total).to.equal(16);
const total = wrapper.find(Bar).reduce((amount, n) => amount ? amount + n.prop('amount') : n.prop('amount'));
Copy link
Member

Choose a reason for hiding this comment

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

actually, on the first iteration amount is the first item - that's the behavior of reduce when omitting the initial value.

Copy link
Member

Choose a reason for hiding this comment

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

in other words, [1, 2, 3].reduce(function (prev, item) { console.log([prev, item]); }); logs [1, 2] and then [undefined, 3]

@ljharb
Copy link
Member

ljharb commented Nov 9, 2016

If enzyme's reduce fails to have the same behavior as Array#reduce, that's a bug we need to fix.

@ljharb
Copy link
Member

ljharb commented Nov 11, 2016

I've put up #673 to fix this bug, thanks for the PR!

@nfcampos
Copy link
Collaborator

@ljharb since we have #673 shouldn't this one be closed?

@ljharb
Copy link
Member

ljharb commented Mar 19, 2017

@nfcampos good call

@ljharb ljharb closed this Mar 19, 2017
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.

3 participants