【问题标题】:Test click event on a "web-component" button with Storybook使用 Storybook 测试 \"web-component\" 按钮上的点击事件
【发布时间】:2023-01-30 19:45:18
【问题描述】:

我正在互联网上寻找有关如何测试的示例点击事件在一个按钮上(网络组件/打字稿) 与故事书,但我找不到一个清晰的。 你能给我推荐一些指南/文章或代码 sn-ps 吗?

我已经创建了故事.ts文件;是这样的:

import { html, TemplateResult } from 'lit';
import './index.ts';
import { Properties } from './model/button.interfaces';

export default {
  title: 'My button',
  component: 'my-button',
};

interface Story<T> {
  (args: T): TemplateResult;
  args?: Partial<T>;
  argTypes?: Record<string, unknown>;
  parameters?: any;
}

interface ArgTypes extends Properties{}

const Template: Story<ArgTypes> = (args: ArgTypes) => html`
      <my-button 
          ?disabled="${args.disabled}"
          color=${args.color}>
        ${args.text}
      </my-button>`

export const Button = Template.bind({});

Button.args = {
  label: "This is the text",
  color: "primary"
}

Button.argTypes = {
  color: {
    control: 'select',
    options: ['primary', 'secondary'],
    table: {
      category: 'Modifiers',
    },
  }, 
  disabled: {
    control: 'boolean',
    options: [true, false],
    table: {
      category: 'Modifiers',
    },
  }
}

谢谢

【问题讨论】:

  • Can you suggest me some guides/articles or code snippets? - 简单地说,不,我们不能。我们帮助您解决问题并调试您的代码,我们无法对不存在的代码执行此操作
  • 我添加了我的代码:(
  • Can you suggest me some guides/articles or code snippets? - 你要求密码
  • 如果您的代码存在问题,请编辑您的问题以这样说,包括 minimal reproducible example 并告诉我们您的错误

标签: typescript web-component storybook


【解决方案1】:

由于 Web 组件作为本机 html 元素工作,您可以将 onclick 属性附加到您的 &lt;my-button&gt;。 尝试在您的组件上方添加一个脚本标记,您在其中定义一个 onclick 处理程序并将其添加到您的组件。

const Template: Story<ArgTypes> = (args: ArgTypes) => html`
      <script>
          const clickHandler = () => console.log('clicked')
      </script>
      <my-button 
          ?disabled="${args.disabled}"
          color=${args.color}
          onclick="clickHandler()">
        ${args.text}
      </my-button>`

现在,无论何时单击按钮,您都应该看到日志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2017-06-20
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 2011-12-30
    相关资源
    最近更新 更多