Skip to content

Commit 283822e

Browse files
committed
add stub flags prop
1 parent 6aba6c5 commit 283822e

2 files changed

Lines changed: 74 additions & 3 deletions

File tree

src/LdProvider.js

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,25 +11,41 @@ type SettingsT = {|
1111
|};
1212

1313
type Props = {|
14+
/**
15+
* Children to render
16+
*/
1417
children?: React.Node,
18+
/**
19+
* Instance of a Launch Darkly client
20+
*/
1521
client?: {
1622
on: (string, Function) => void,
1723
allFlags: () => FlagsT,
1824
waitForInitialization: () => Promise<void>,
1925
...
2026
},
27+
/**
28+
* Whether the children should render before the client has returns the list of flags
29+
*/
2130
async?: boolean,
31+
/**
32+
* An object list of flags and their respective return value, useful for mock testing
33+
*/
34+
stubbedFlags?: {
35+
[key: string]: any,
36+
},
2237
|};
2338

2439
const LdProvider = ({
2540
children = null,
2641
client,
2742
async = false,
43+
stubbedFlags,
2844
}: Props): React.Node => {
29-
const [flags, setFlags] = React.useState<FlagsT | void>();
45+
const [flags, setFlags] = React.useState<FlagsT | void>(stubbedFlags);
3046

3147
React.useEffect(() => {
32-
if (!client) return;
48+
if (!client || stubbedFlags) return;
3349

3450
const mapToCurrentFlags = (
3551
settings: SettingsT,
@@ -50,7 +66,7 @@ const LdProvider = ({
5066
...mapToCurrentFlags(settings),
5167
}));
5268
});
53-
}, [client]);
69+
}, [client, stubbedFlags]);
5470

5571
if (!flags && !async) return null;
5672

src/LdProvider.spec.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,59 @@ describe('useLdFlag', () => {
112112

113113
expect(container.textContent).toBe('');
114114
});
115+
116+
it('returns a list of mock flags', () => {
117+
const App = () => {
118+
const enableTest = useLdFlag('enableTest');
119+
120+
return (
121+
<div data-testid="test">
122+
{enableTest ? 'true' : 'false'}
123+
</div>
124+
);
125+
};
126+
127+
const flags = {
128+
enableTest: true,
129+
notEnabledTest: false,
130+
};
131+
132+
const { getByTestId } = render(
133+
<LdProvider
134+
stubbedFlags={flags}
135+
>
136+
<App />
137+
</LdProvider>,
138+
);
139+
140+
expect(getByTestId('test').textContent).toBe('true');
141+
});
142+
143+
it('ignores client when mock flags are passed', () => {
144+
const App = () => {
145+
const enableTest = useLdFlag('enableTest');
146+
147+
return (
148+
<div data-testid="test">
149+
{enableTest ? 'true' : 'false'}
150+
</div>
151+
);
152+
};
153+
154+
const flags = {
155+
enableTest: true,
156+
notEnabledTest: false,
157+
};
158+
159+
const { getByTestId } = render(
160+
<LdProvider
161+
stubbedFlags={flags}
162+
client={({}: any)}
163+
>
164+
<App />
165+
</LdProvider>,
166+
);
167+
168+
expect(getByTestId('test').textContent).toBe('true');
169+
});
115170
});

0 commit comments

Comments
 (0)