2021 November 10thHandling `undefined` in Jest and Typescriptjest, testing, typescript,
Handling undefined
in Jest and Typescript
You may come across the following error Argument of type x | undefined is not assignable to parameter of type undefined
in your Jest tests. Kent Dodds resolves this with a type guard.
test("renders an input text field with a label", () => {
// need "as" because of https://github.com/storybookjs/storybook/issues/13747
const args = InputWithLabel.args as TInputProps;
render(<InputWithLabel {...args} />);
if (!args.label) {
throw new Error("🚨 Make sure label args in story is defined.");
}
const label = args.label;
const input = screen.getByLabelText(label);
expect(input).toHaveAttribute("type", "text");
});