Button
import React from 'react';
import './button.css';
interface ButtonProps {
primary?: boolean;
backgroundColor?: string;
size?: 'small' | 'medium' | 'large';
label: string;
onClick?: () => void;
}
export const Button = ({
primary = false,
size = 'medium',
backgroundColor,
label,
...props
}: ButtonProps) => {
const mode = primary ? 'storybook-button--primary' : 'storybook-button--secondary';
return (
<button
type="button"
className={['storybook-button', `storybook-button--${size}`, mode].join(' ')}
style={{ backgroundColor }}
{...props}
>
{label}
</button>
);
};
Button.stories
import React from 'react';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import { Button } from '.';
export default {
title: 'Example/Button',
component: Button,
argTypes: {
backgroundColor: { control: 'color' },
},
} as ComponentMeta<typeof Button>;
const Template: ComponentStory<typeof Button> = (args) => <Button {...args} />;
export const Primary = Template.bind({});
Primary.args = {
primary: true,
label: 'Button',
};
...
Button.test
import { render } from '@testing-library/react';
import { Button } from '.';
import { Primary } from './Button.stories';
test('should render a button', () => {
render(<Button label="Click Me!" />);
});
test('should render a primary button', () => {
if (typeof Primary.args === 'undefined') {
throw new Error('Args is undfeined');
} else if (typeof Primary.args.label !== 'string') {
throw new Error('The type of label is not string');
} else if (Primary.args.label === undefined) {
return;
}
/**
Types of property 'label' are incompatible.
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
*/
render(<Primary {...Primary.args} />);
});
I wrote some test code for the button component that was made by Storybook default.
Even though I already checked the type of the label prop if the type is undefined or not before the props are delivered, it throws a syntax error 'string | undefined' is not assignable to type 'string'.
Why did I do wrong?