0

谁能指出我正确的方向?

我期待在点击事件被触发后调用模拟函数。我得到的是: 预期电话数:1 接听电话数:0

这是我的组件以及测试文件:

EventTestingWrapper.svelte

<script>
  export let testComponent
  export let clickHandler
</script>

<div data-testid="testing-wrapper">
  <svelte:component this={testComponent} on:click={clickHandler} />
</div>

模态.svelte

<div
  class="modal-background"
  data-testid="modal-background"
  on:click|self={close}
>
lorem 
</div>

模态测试.js

test('trying out test wrapper',()=>{

    const clickHandler = jest.fn();
  
    const { getByTestId } = render(EventTestingWrapper, {testComponent: Modal, clickHandler})
    const modalBackground = getByTestId('modal-background')
    const clickEvent = createEvent.click(modalBackground)

    fireEvent(modalBackground, clickEvent);

    expect(modalBackground).toBeInTheDocument()
    expect(clickHandler).toHaveBeenCalledTimes(1)
  })
4

1 回答 1

1

我不确切知道这是否是您想要的,但是要将:click 类型的事件侦听器传递给@testing-library/svelte呈现的组件,您必须使用component.$on语法。

例如:

describe('Button', () => {
  it('should render correctly', async () => {
    const results = render(Button)
    const onClick = jest.fn()
    results.component.$on('click', onClick)

    const button = results.container.querySelector('button')
    expect(button).not.toBeNull()

    // Using await when firing events is unique to the svelte testing library because
    // we have to wait for the next `tick` so that Svelte flushes all pending state changes.
    await fireEvent.click(button as HTMLElement)

    expect(results.container).toBeInTheDocument()
    expect(onClick.mock.calls.length).toEqual(1)
  })
})

测试库文档中的这个链接似乎非常有用https://sveltesociety.dev/recipes/testing-and-debugging/unit-testing-svelte-component/

于 2021-07-04T08:52:49.710 回答