reactjs 如何使用jest和jsdom测试lit-html中的事件和样式unsafecss

nc1teljy  于 2023-01-04  发布在  React
关注(0)|答案(1)|浏览(139)

我正在尝试使用jest为我的lit-html元素创建一个单元测试,我想检查一下click事件是否按预期工作。
测试单击时从活动变为禁用的事件。

// my-lit-html-toggle.ts
const TAG = 'my-lit-html-toggle';

@customElement(TAG)
export class My-lit-htmToggle extends LitElement {
  @property({ type: Boolean })
  public active = false;

  @property({ type: Boolean })
  public disabled = false;

  public static styles = unsafeCSS(toggleSwitchStyles);

  public render(): TemplateResult {
    const classes = {
      active: this.active,
      disabled: this.disabled,
    };
    return html`
      <div class="toggle ${classMap(classes)}" @click=${this.toggleActive}>
        <div class="toggle-switch"></div>
        <div class="toggle-handle"></div>
      </div>
    `;
  }

  private toggleActive() {
    const onToggle = new CustomEvent<ToggleSwitchEvent>('onToggle', {
      detail: {
        active: (this.active = !this.active),
      },
    });
    this.dispatchEvent(onToggle);
  }
}
// Test JEST
import { html, render } from 'lit'; 

describe('Given my-lit-html-toggle', () => {

    it('Should switch from active to disabled', async function () {
      const switchHandler = jest.fn();

      render(html`<my-lit-html-toggle active .click="${switchHandler}" ></my-lit-html-toggle>`, document.body);
      await Promise.resolve();
      document.body.querySelector(TAGNAME)?.click()
      await waitFor(() => expect(switchHandler).toBeCalledTimes(1));
    });
})

已调用单击事件,但类未更改。Jest错误:

expect(element).toHaveClass("disbled")

    Expected the element to have class:
      disbled
    Received:
      toggle-switch active

      38 |       );
      39 |       const cut = document.body.querySelector(TAGNAME)?.shadowRoot;
    > 40 |       expect(cut?.childNodes.item(2)).toHaveClass('disbled');
         |                                       ^
      41 |     });
      42 |
bkhjykvo

bkhjykvo1#

经调查,jest中的describe方法错误。此代码不会触发my-lit-html-toggle.ts中的事件,因为jest不知道***.click***是什么。活动和非活动状态是在事件后设置的,而不是作为属性设置的。
方法不正确

it('Should switch from active to disabled', async function () {
  const switchHandler = jest.fn();

  render(html`<my-lit-html-toggle active .click="${switchHandler}">
              </my-lit-html-toggle>`, document.body);
  await Promise.resolve();

  document.body.querySelector(TAGNAME)?.click()
  await waitFor(() => expect(switchHandler).toBeCalledTimes(1));
});

使用正确的解决方案***@click=${(例如:自定义事件)=〉单击(例如详细信息)}***

it('Should switch from active to disabled', async function () {
 const onclick = jest.fn()

   render(html`<my-lit-html-toggle @click=${(e: CustomEvent) => onclick(e.detail)}>
              </my-lit-html-toggle>`, document.body);
   await Promise.resolve();

  document.body.querySelector(TAGNAME)?.click()
  await waitFor(() => expect(onclick).toBeCalledTimes(1));
});

相关问题