From 10068aecc1b13c276d82b81482331813d3e5fb2f Mon Sep 17 00:00:00 2001 From: Martin Veith Date: Mon, 3 Feb 2020 23:08:43 +0100 Subject: [PATCH] Update for NaN comparison --- src/Countdown.test.tsx | 34 +++++++++++++++++++++++++++++++++- src/Countdown.tsx | 15 ++++++++++----- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/src/Countdown.test.tsx b/src/Countdown.test.tsx index 08fa98b..0dbc750 100644 --- a/src/Countdown.test.tsx +++ b/src/Countdown.test.tsx @@ -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'; @@ -179,6 +179,38 @@ describe('', () => { expect(api.isCompleted()).toBe(true); }); + it('should only re-set time delta state when props have changed', () => { + const root = document.createElement('div'); + wrapper = mount(, { attachTo: root }); + const obj = wrapper.instance(); + obj.setTimeDeltaState = jest.fn(); + + function mergeProps(partialProps: Partial): 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); diff --git a/src/Countdown.tsx b/src/Countdown.tsx index e5d6769..376267c 100644 --- a/src/Countdown.tsx +++ b/src/Countdown.tsx @@ -206,12 +206,17 @@ export default class Countdown extends React.Component 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 + ); + }) ); }