Skip to content

test: count re-renders #200

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@
"author": "",
"license": "Apache-2.0",
"devDependencies": {
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.1.4",
"@testing-library/react": "^14.1.2",
"@testing-library/react": "^16.3.0",
"@testing-library/react-hooks": "^8.0.1",
"@testing-library/user-event": "^14.6.1",
"@types/react": "^18.2.38",
"@vitest/coverage-istanbul": "^0.34.6",
"happy-dom": "^12.10.3",
Expand Down
12 changes: 3 additions & 9 deletions src/FlagContext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { type startTransition } from 'react';
import type { UnleashClient } from 'unleash-proxy-client';

export interface IFlagContextValue
Expand All @@ -7,14 +7,8 @@ export interface IFlagContextValue
'on' | 'off' | 'updateContext' | 'isEnabled' | 'getVariant'
> {
client: UnleashClient;
flagsReady: boolean;
setFlagsReady: React.Dispatch<
React.SetStateAction<IFlagContextValue['flagsReady']>
>;
flagsError: any;
setFlagsError: React.Dispatch<
React.SetStateAction<IFlagContextValue['flagsError']>
>;
isInitiallyReady: boolean;
startTransition: typeof startTransition;
}

const FlagContext = React.createContext<IFlagContextValue | null>(null);
Expand Down
59 changes: 0 additions & 59 deletions src/FlagProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -186,64 +186,6 @@ test('A memoized consumer should not rerender when the context provider values a
expect(renderCounter).toHaveBeenCalledTimes(1);
});

test('should update when ready event is sent', () => {
const localMock = vi.fn();
UnleashClientSpy.mockReturnValue({
getVariant: getVariantMock,
updateContext: updateContextMock,
start: startClientMock,
stop: stopClientMock,
isEnabled: isEnabledMock,
on: localMock,
off: offMock,
});

const client = new UnleashClient(givenConfig);

render(
<FlagProvider unleashClient={client}>
<div>Hi</div>
</FlagProvider>
);

localMock.mockImplementation((event, cb) => {
if (event === EVENTS.READY) {
cb();
}
});

expect(localMock).toHaveBeenCalledWith(EVENTS.READY, expect.any(Function));
});

test('should register error when error event is sent', () => {
const localMock = vi.fn();
UnleashClientSpy.mockReturnValue({
getVariant: getVariantMock,
updateContext: updateContextMock,
start: startClientMock,
stop: stopClientMock,
isEnabled: isEnabledMock,
on: localMock,
off: offMock,
});

const client = new UnleashClient(givenConfig);

render(
<FlagProvider unleashClient={client}>
<div>Hi</div>
</FlagProvider>
);

localMock.mockImplementation((event, cb) => {
if (event === EVENTS.ERROR) {
cb('Error');
}
});

expect(localMock).toHaveBeenCalledWith(EVENTS.ERROR, expect.any(Function));
});

test('should not start client if startClient is false', () => {
const localMock = vi.fn();
const stopMock = vi.fn();
Expand Down Expand Up @@ -282,7 +224,6 @@ test('should not start client if startClient is false when passing config', () =
off: offMock,
});


render(
<FlagProvider config={givenConfig} startClient={false}>
<div>Hi</div>
Expand Down
105 changes: 19 additions & 86 deletions src/FlagProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ const offlineConfig: IConfig = {

// save startTransition as var to avoid webpack analysis (https://github.com/webpack/webpack/issues/14814)
const _startTransition = 'startTransition';
// fallback for React <18 which doesn't support startTransition
// Fallback for React <18 and exclude startTransition if in React Native
const defaultStartTransition = React[_startTransition] || (fn => fn());

Expand All @@ -39,111 +38,45 @@ const FlagProvider: FC<PropsWithChildren<IFlagProvider>> = ({
const client = React.useRef<UnleashClient>(
unleashClient || new UnleashClient(config)
);
const [flagsReady, setFlagsReady] = React.useState(
Boolean(
unleashClient
? (customConfig?.bootstrap && customConfig?.bootstrapOverride !== false) || unleashClient.isReady?.()
: config.bootstrap && config.bootstrapOverride !== false
)
);
const [flagsError, setFlagsError] = useState(client.current.getError?.() || null);

useEffect(() => {
if (!config && !unleashClient) {
console.error(
`You must provide either a config or an unleash client to the flag provider.
If you are initializing the client in useEffect, you can avoid this warning
by checking if the client exists before rendering.`
);
}

const errorCallback = (e: any) => {
startTransition(() => {
setFlagsError((currentError: any) => currentError || e);
});
};

const clearErrorCallback = (e: any) => {
startTransition(() => {
setFlagsError(null);
});
}

let timeout: ReturnType<typeof setTimeout> | null = null;
const readyCallback = () => {
// wait for flags to resolve after useFlag gets the same event
timeout = setTimeout(() => {
startTransition(() => {
setFlagsReady(true);
});
}, 0);
};

client.current.on('ready', readyCallback);
client.current.on('error', errorCallback);
client.current.on('recovered', clearErrorCallback);

if (startClient) {
// defensively stop the client first
client.current.stop();
// start the client
client.current.start();
}

// stop unleash client on unmount
return function cleanup() {
if (client.current) {
client.current.off('error', errorCallback);
client.current.off('ready', readyCallback);
client.current.off('recovered', clearErrorCallback);
if (stopClient) {
client.current.stop();
}
}
if (timeout) {
clearTimeout(timeout);
if (stopClient) {
client.current.stop();
}
};
}, []);

const on = useCallback<IFlagContextValue['on']>(client.current.on, []);

const off = useCallback<IFlagContextValue['off']>(client.current.off, []);

const isEnabled = useCallback<IFlagContextValue['isEnabled']>(
(toggleName: string) => client.current.isEnabled(toggleName),
[]
)

const updateContext = useCallback<IFlagContextValue['updateContext']>(
async (context: IMutableContext) =>
await client.current.updateContext(context),
[]
)

const getVariant = useCallback<IFlagContextValue['getVariant']>(
(toggleName: string) => client.current.getVariant(toggleName),
[]
)

const context = useMemo<IFlagContextValue>(
const value = useMemo(
() => ({
on,
off,
updateContext,
isEnabled,
getVariant,
on: ((...args) => client.current.on(...args)) as IFlagContextValue['on'],
off: ((...args) => client.current.off(...args)) as IFlagContextValue['off'],
updateContext: (async(...args) => await client.current.updateContext(...args)) as IFlagContextValue['updateContext'],
isEnabled: ((...args) => client.current.isEnabled(...args)) as IFlagContextValue['isEnabled'],
getVariant: ((...args) => client.current.getVariant(...args)) as IFlagContextValue['getVariant'],

client: client.current,
flagsReady,
flagsError,
setFlagsReady,
setFlagsError,
isInitiallyReady: Boolean(
unleashClient
? (customConfig?.bootstrap &&
customConfig?.bootstrapOverride !== false) ||
unleashClient.isReady?.()
: config.bootstrap && config.bootstrapOverride !== false
),
startTransition,
}),
[flagsReady, flagsError, on, off, updateContext, isEnabled, getVariant]
[]
);

return (
<FlagContext.Provider value={context}>{children}</FlagContext.Provider>
<FlagContext.Provider value={value}>{children}</FlagContext.Provider>
);
};

Expand Down
Loading
Loading