8000 [FSSDK-9871] Hook for track events by junaed-optimizely · Pull Request #268 · optimizely/react-sdk · GitHub
[go: up one dir, main page]

Skip to content

[FSSDK-9871] Hook for track events #268

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

Merged
merged 6 commits into from
Jul 9, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
[FSSDK-9871] useTrackEvents hook + test improvement
  • Loading branch information
junaed-optimizely committed Jul 8, 2024
commit 17b9ce1dab728f1b81950375344c55bea6b35f7c
46 changes: 35 additions & 11 deletions src/hooks.spec.tsx
8000
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,8 @@ import '@testing-library/jest-dom/extend-expect';

import { OptimizelyProvider } from './Provider';
import { OnReadyResult, ReactSDKClient, VariableValuesObject } from './client';
import { useExperiment, useFeature, useDecision, useTrackEvents } from './hooks';
import { useExperiment, useFeature, useDecision, useTrackEvents, hooksLogger } from './hooks';
import { OptimizelyDecision } from './utils';

const defaultDecision: OptimizelyDecision = {
enabled: false,
variables: {},
Expand Down Expand Up @@ -80,7 +79,7 @@ describe('hooks', () => {
let forcedVariationUpdateCallbacks: Array<() => void>;
let decideMock: jest.Mock<OptimizelyDecision>;
let setForcedDecisionMock: jest.Mock<void>;

let hooksLoggerErrorSpy: jest.SpyInstance;
const REJECTION_REASON = 'A rejection reason you should never see in the test runner';

beforeEach(() => {
Expand All @@ -99,7 +98,6 @@ describe('hooks', () => {
);
}, timeout || mockDelay);
});

activateMock = jest.fn();
isFeatureEnabledMock = jest.fn();
featureVariables = mockFeatureVariables;
Expand All @@ -110,8 +108,7 @@ describe('hooks', () => {
forcedVariationUpdateCallbacks = [];
decideMock = jest.fn();
setForcedDecisionMock = jest.fn();
// subscribeToInitialization = jest.fn();

hooksLoggerErrorSpy = jest.spyOn(hooksLogger, 'error');
optimizelyMock = ({
activate: activateMock,
onReady: jest.fn().mockImplementation(config => getOnReadyPromise(config || {})),
Expand Down Expand Up @@ -170,6 +167,7 @@ describe('hooks', () => {
res => res.dataReadyPromise,
err => null
);
hooksLoggerErrorSpy.mockReset();
});

describe('useExperiment', () => {
Expand Down Expand Up @@ -1051,26 +1049,52 @@ describe('hooks', () => {
});
});
describe('useTrackEvents', () => {
it('returns null and false states when optimizely is not provided', () => {
it('returns track method and false states when optimizely is not provided', () => {
const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => {
//@ts-ignore
return <OptimizelyProvider>{children}</OptimizelyProvider>;
};
const { result } = renderHook(() => useTrackEvents(), { wrapper });
expect(result.current).toEqual([null, false, false]);
expect(result.current[0]).toBeInstanceOf(Function);
expect(result.current[1]).toBe(false);
expect(result.current[2]).toBe(false);
});

it('returns track method along with clientReady while optimizely instance is provided', async () => {
it('returns track method along with clientReady and didTimeout state when optimizely instance is provided', () => {
const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => (
<OptimizelyProvider optimizely={optimizelyMock} isServerSide={false} timeout={10000}>
{children}
</OptimizelyProvider>
);

const { result } = renderHook(() => useTrackEvents(), { wrapper });
expect(result.current[0]).toBeInstanceOf(Function);
expect(typeof result.current[1]).toBe('boolean');
expect(typeof result.current[2]).toBe('boolean');
});

expect(result.current[1]).toBe(true);
expect(result.current[2]).toBe(false);
it('Log error when track method is called and optimizely instance is not provided', () => {
const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => {
//@ts-ignore
return <OptimizelyProvider>{children}</OptimizelyProvider>;
};
const { result } = renderHook(() => useTrackEvents(), { wrapper });
result.current[0]('eventKey');
expect(hooksLogger.error).toHaveBeenCalledTimes(1);
});

it('Log error when track method is called and client is not ready', () => {
optimizelyMock.isReady = jest.fn().mockReturnValue(false);

const wrapper = ({ children }: { children: React.ReactNode }): React.ReactElement => (
<OptimizelyProvider optimizely={optimizelyMock} isServerSide={false} timeout={10000}>
{children}
</OptimizelyProvider>
);

const { result } = renderHook(() => useTrackEvents(), { wrapper });
result.current[0]('eventKey');
expect(hooksLogger.error).toHaveBeenCalledTimes(1);
});
});
});
36 changes: 23 additions & 13 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { notifier } from './notifier';
import { OptimizelyContext } from './Context';
import { areAttributesEqual, OptimizelyDecision, createFailedDecision } from './utils';

const hooksLogger = getLogger('ReactSDK');
export const hooksLogger = getLogger('ReactSDK');

enum HookType {
EXPERIMENT = 'Experiment',
Expand Down Expand Up @@ -87,7 +87,9 @@ interface UseDecision {
];
}

type UseTrackEvents = () => [null, false, false] | [ReactSDKClient['track'], ClientReady, DidTimeout];
interface UseTrackEvents {
(): [(...args: Parameters<ReactSDKClient['track']>) => void, boolean, boolean];
}

interface DecisionInputs {
entityKey: string;
Expand Down Expand Up @@ -503,23 +505,34 @@ export const useDecision: UseDecision = (flagKey, options = {}, overrides = {})
return [state.decision, state.clientReady, state.didTimeout];
};


export const useTrackEvents: UseTrackEvents = () => {
const { optimizely, isServerSide, timeout } = useContext(OptimizelyContext);
const isClientReady = !!(isServerSide || optimizely?.isReady());

const track = useCallback(
(...rest: Parameters<ReactSDKClient['track']>): void => {
if (!optimizely) {
hooksLogger.error(`Unable to track events. optimizely prop must be supplied via a parent <OptimizelyProvider>`);
return;
}
if (!isClientReady) {
hooksLogger.error(`Unable to track events. Optimizely client is not ready yet.`);
return;
}
optimizely.track(...rest);
},
[optimizely, isClientReady]
);

if (!optimizely) {
hooksLogger.error(`Unable to track events. optimizely prop must be supplied via a parent <OptimizelyProvider>`);
return [null, false, false];
return [track, false, false];
}
const isClientReady = isServerSide || optimizely.isReady();

const [state, setState] = useState<{
track: ReactSDKClient['track'];
clientReady: boolean;
didTimeout: DidTimeout;
}>(() => {
return {
track: optimizely.track,
clientReady: isClientReady,
didTimeout: false,
};
Expand All @@ -533,13 +546,10 @@ export const useTrackEvents: UseTrackEvents = () => {
// was provided as a promise and we need to subscribe and wait for user to become available.
if (optimizely.getIsUsingSdkKey() || !isClientReady) {
subscribeToInitialization(optimizely, timeout, initState => {
setState({
track: optimizely.track,
...initState,
});
setState(initState);
});
}
}, []);

return [state.track, state.clientReady, state.didTimeout];
return [track, state.clientReady, state.didTimeout];
};
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
export { OptimizelyContext, OptimizelyContextConsumer, OptimizelyContextProvider } from './Context';
export { OptimizelyProvider } from './Provider';
export { OptimizelyFeature } from './Feature';
export { useFeature, useExperiment, useDecision } from './hooks';
export { useFeature, useExperiment, useDecision, useTrackEvents } from './hooks';
export { withOptimizely, WithOptimizelyProps, WithoutOptimizelyProps } from './withOptimizely';
export { OptimizelyExperiment } from './Experiment';
export { OptimizelyVariation } from './Variation';
Expand Down
0