0

我正在编写一个input组件,并且在测试单击或按键stencil时触发的发出事件时遇到了麻烦。组件:enter

    export class Input {
    .
    .
      private inputRef?: HTMLInputElement;
      @Event() inputEvent: EventEmitter<{}>;
    .
    .
    render() {
     return (
      <div class="status">
          <div class="input-wrapper">
            <input onKeyUp = {event => this.handleKeyDown(event)} ref={el => this.inputRef = el as HTMLInputElement}/>
          </div>
      </div>);
     }
      private handleKeyDown(e: KeyboardEvent): void {
        this.dispatchSearchEvent(e);
      }

      private dispatchSearchEvent(e){
        this.inputEvent.emit({type: "event-name", event: e, data: (this.inputRef as HTMLInputElement).value});
      }
    }

conponent.spec.jsx:

  it('fires an event upon enter key press', async () => {
    const component = new InputFields();
    jest.spyOn(component, 'event-name');

      const keyUpEvent = new Event("keyup", {
        key: "enter",
        keyCode: 13,
        which: 13,
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
      });

      keyUpEvent.target = {value: "some input value"}
      component.handleKeyDown(keyUpEvent);
  
      component.inputEvent = { emit: jest.fn().mockReturnValue(Promise.resolve()), };

      expect(component.inputEvent.emit).toHaveBeenCalled();
  });

有一个错误:

Cannot spy the event-name property because it is not a function; undefined given instead

  356 |   it('fires an event upon enter key press', async () => {
  357 |     const component = new Input();
> 358 |     jest.spyOn(component, 'event-name');
      |          ^
  359 |
  360 |       const keyUpEvent = new Event("keyup", {
  361 |         key: "enter",
4

1 回答 1

1

错误消息试图告诉您您的Input组件没有名为event-name. spyOn用于监视功能而不是事件。

在 E2E 测试中,您可以E2EElement.spyOnEvent用于事件:

const page = await newE2EPage({html: '<my-input></my-input>'});
const component = await page.find('my-input');
const spy = await component.spyOnEvent('inputEvent');
await component.type('x');
expect(spy).toHaveReceivedEventTimes(1);
expect(spy.firstEvent.detail.data).toBe('x');
于 2022-02-11T16:50:57.183 回答