Skip to content

Commit

Permalink
fix: Use nullish coalescing operator in useParameter(..)
Browse files Browse the repository at this point in the history
The `useParameter(..)` hook accepts a key and a default value. It then
provides the default value if the current story has not provided a
desired value for the relevant `parameters` object.

This change updates the logic of when to fall back to the default. The
old logic used a boolean operator (`||`), which worked as long as the
provided value wasn't falsey. Instead, account for this by using the
nullish coalescing operator (`??`).
  • Loading branch information
evancharlton committed Jan 25, 2022
1 parent b82ecb5 commit 09d44bc
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
57 changes: 57 additions & 0 deletions lib/addons/src/hooks.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { useParameter, useStoryContext } from './hooks';

const { window: globalWindow } = global;

describe('addons/hooks', () => {
beforeEach(() => {
globalWindow.STORYBOOK_HOOKS_CONTEXT = undefined;
});

afterEach(() => {
globalWindow.STORYBOOK_HOOKS_CONTEXT = undefined;
});

describe('useStoryContext', () => {
test('should throw', () => {
expect(() => useStoryContext()).toThrowError(
'Storybook preview hooks can only be called inside decorators and story functions.'
);
});
});

describe('useParameter', () => {
beforeEach(() => {
globalWindow.STORYBOOK_HOOKS_CONTEXT = {
currentContext: {
parameters: {
'undefined key': undefined,
'null key': null,
'false key': false,
'zero key': 0,
'object key': { defined: true },
},
},
};
});

test('undefined key', () => {
expect(useParameter('undefined key', 'undefined default')).toEqual('undefined default');
});

test('null key', () => {
expect(useParameter('null key', 'null default')).toEqual('null default');
});

test('false key', () => {
expect(useParameter('false key', 'false default')).toEqual(false);
});

test('zero key', () => {
expect(useParameter('zero key', 'zero default')).toEqual(0);
});

test('object key', () => {
expect(useParameter('object key', 'object default')).toMatchObject({ defined: true });
});
});
});
2 changes: 1 addition & 1 deletion lib/addons/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ export function useStoryContext<TFramework extends AnyFramework>(): StoryContext
export function useParameter<S>(parameterKey: string, defaultValue?: S): S | undefined {
const { parameters } = useStoryContext();
if (parameterKey) {
return parameters[parameterKey] || (defaultValue as S);
return parameters[parameterKey] ?? (defaultValue as S);
}
return undefined;
}
Expand Down

0 comments on commit 09d44bc

Please sign in to comment.