import { expect } from "chai" ; import * as sinon from "sinon" ; import { renderHook } from "@testing-library/react-hooks" ; import { useEffectSkipFirst } from "../../../core-react/utils/hooks/useEffectSkipFirst" ; describe ( "useEffectSkipFirst" , ( ) => { it ( "does not invoke callback on first effect" , ( ) => { const spy = sinon . spy ( ) ; renderHook ( ( props ) => useEffectSkipFirst ( props . callback , props . deps ) , { initialProps : { callback : spy , deps : [ true ] } } ) ; expect ( spy ) . to . not . be . called ; } ) ; it ( "does not invoke cleanup if callback was not invoked" , ( ) => { const cleanupSpy = sinon . spy ( ) ; const callback = ( ) => cleanupSpy ; const { unmount } = renderHook ( ( props ) => useEffectSkipFirst ( props . callback , props . deps ) , { initialProps : { callback , deps : [ true ] } } ) ; unmount ( ) ; expect ( cleanupSpy ) . to . not . be . called ; } ) ; it ( "invokes callback when dependencies change" , ( ) => { const spy = sinon . spy ( ) ; const { rerender } = renderHook ( ( props ) => useEffectSkipFirst ( props . callback , props . deps ) , { initialProps : { callback : spy , deps : [ true ] } } ) ; expect ( spy ) . to . not . be . called ; rerender ( { callback : spy , deps : [ false ] } ) ; expect ( spy ) . to . be . calledOnce ; } ) ; it ( "invokes cleanup if callback was invoked" , ( ) => { const cleanupSpy = sinon . spy ( ) ; let callbackInvokeCount = 0 ; const callback = ( ) => { callbackInvokeCount ++ ; return cleanupSpy ; } ; const { rerender , unmount } = renderHook ( ( props ) => useEffectSkipFirst ( props . callback , props . deps ) , { initialProps : { callback , deps : [ true ] } } ) ; expect ( callbackInvokeCount ) . to . be . eq ( 0 ) ; rerender ( { callback , deps : [ false ] } ) ; expect ( callbackInvokeCount ) . to . be . eq ( 1 ) ; expect ( cleanupSpy ) . to . not . be . called ; unmount ( ) ; expect ( callbackInvokeCount ) . to . be . eq ( 1 ) ; expect ( cleanupSpy ) . to . be . calledOnce ; } ) ; it ( "invokes cleanup if callback was invoked multiple times" , ( ) => { const cleanupSpy = sinon . spy ( ) ; let callbackInvokeCount = 0 ; const callback = ( ) => { callbackInvokeCount ++ ; return cleanupSpy ; } ; const { rerender , unmount } = renderHook ( ( props ) => useEffectSkipFirst ( props . callback , props . deps ) , { initialProps : { callback , deps : [ true ] } } ) ; expect ( callbackInvokeCount ) . to . be . eq ( 0 ) ; expect ( cleanupSpy ) . to . not . be . called ; rerender ( { callback , deps : [ false ] } ) ; expect ( callbackInvokeCount ) . to . be . eq ( 1 ) ; expect ( cleanupSpy ) . to . not . be . called ; rerender ( { callback , deps : [ true ] } ) ; expect ( callbackInvokeCount ) . to . be . eq ( 2 ) ; expect ( cleanupSpy ) . to . be . calledOnce ; unmount ( ) ; expect ( callbackInvokeCount ) . to . be . eq ( 2 ) ; expect ( cleanupSpy ) . to . be . calledTwice ; } ) ; } ) ;