【问题标题】:Unit test for Svelte on:click eventSvelte on:click 事件的单元测试
【发布时间】:2021-08-08 14:33:10
【问题描述】:

谁能指出我正确的方向?

我希望在点击事件触发后调用模拟函数。 我所拥有的是: 预计通话次数: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>

Modal.svelte

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

Modal.test.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)
  })

【问题讨论】:

    标签: jestjs svelte-3 testing-library


    【解决方案1】:

    我不知道这是否是您想要的,但是要将:单击类型事件侦听器传递给@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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-08
      • 2019-10-09
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 2021-10-25
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多