Skip to content

Commit

Permalink
Update for NaN comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
ndresx committed Feb 3, 2020
1 parent 7c2bf24 commit 10068ae
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
34 changes: 33 additions & 1 deletion src/Countdown.test.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react';
import { mount } from 'enzyme';

import Countdown from './Countdown';
import Countdown, { CountdownProps } from './Countdown';
import { calcTimeDelta, formatTimeDelta } from './utils';

import { CountdownProps as LegacyCountdownProps } from './LegacyCountdown';
Expand Down Expand Up @@ -179,6 +179,38 @@ describe('<Countdown />', () => {
expect(api.isCompleted()).toBe(true);
});

it('should only re-set time delta state when props have changed', () => {
const root = document.createElement('div');
wrapper = mount(<Countdown date={1000} />, { attachTo: root });
const obj = wrapper.instance();
obj.setTimeDeltaState = jest.fn();

function mergeProps(partialProps: Partial<CountdownProps>): CountdownProps {
return { ...wrapper.props(), ...partialProps };
}

wrapper.setProps(mergeProps({ date: 500 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(1);

wrapper.setProps(mergeProps({ intervalDelay: 999 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(2);

wrapper.setProps(mergeProps({ date: 500 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(2);

wrapper.setProps(mergeProps({ precision: NaN }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(3);

wrapper.setProps(mergeProps({ precision: NaN }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(3);

wrapper.setProps(mergeProps({ precision: 3 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(4);

wrapper.setProps(mergeProps({ date: 750 }));
expect(obj.setTimeDeltaState).toHaveBeenCalledTimes(5);
});

it('should not (try to) set state after component unmount', () => {
expect(wrapper.state().timeDelta.completed).toBe(false);

Expand Down
15 changes: 10 additions & 5 deletions src/Countdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,17 @@ export default class Countdown extends React.Component<CountdownProps, Countdown
};

shallowCompareProps(propsA: CountdownProps, propsB: CountdownProps): boolean {
const propsAKeys = Object.keys(propsA);
const keysA = Object.keys(propsA);
return (
propsAKeys.length === Object.keys(propsB).length &&
propsAKeys.every(
propAKey => propsB.hasOwnProperty(propAKey) && propsA[propAKey] === propsB[propAKey]
)
keysA.length === Object.keys(propsB).length &&
!keysA.some(keyA => {
const valueA = propsA[keyA];
const valueB = propsB[keyA];
return (
!propsB.hasOwnProperty(keyA) ||
!(valueA === valueB || (valueA !== valueA && valueB !== valueB)) // NaN !== NaN
);
})
);
}

Expand Down

0 comments on commit 10068ae

Please sign in to comment.