在Svelte中为Jest测试访问组件的道具

时间:2020-06-18 16:07:56

标签: javascript testing jestjs svelte svelte-component

问题:如何使用玩笑测试访问苗条组件的道具。例如,如果苗条的组件如下:

ExampleComponent.svelte

    <script>
    import { createEventDispatcher } from 'svelte'

    const dispatch = createEventDispatcher()
    export let booleanProp

    const toggle = () => {
        dispatch('toggle')
    }
</script>

<style lang="scss" src="./style.scss">
</style>

<button class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>
    <svg class="toggle-icon">
        {#if booleanProp}
            <use xlink:href="icons/some-icon.svg" />
        {:else}
            <use xlink:href="icons/some-other-icon.svg" />
        {/if}
    </svg>
</button>

1 个答案:

答案 0 :(得分:1)

属性是与外部世界的接口。模拟:

示例1)模拟道具

    test("should render articles", () => {
  const booleanProp = " I am true";
  const { container, getByText } = render(ExampleComponent, {
    props: {
      articles: [
        {
          booleanProp
        }
      ]
    }
  });

  expect(container.querySelector("a").href).toBe(
    `http://localhost/${canonical_url}`
  );
  expect(getByText(myBool)).toBeInTheDocument();
});

好文章:https://dev.to/jpblancodb/testing-svelte-components-with-jest-53h3

示例2)模拟DOM

用于测试按钮后面的功能。 HTML代码具有必要的元素,以使调用的函数完成其工作:

   it('testFunctionModifiesDom', async () => {
        const documentHTML = 
            '<!doctype html><html><body>' +
            '<my-custom-element>' +
            '<input id="id0" value="true"/>' +. 
            '</my-custom-element>' +
            '</body></html>';
        document.body.innerHTML = documentHTML;

        const myCustomElement = document.querySelector('my-custom-element');

        let actual = myCustomElementsService.toggleMyBoolEffectsElement();

        expect(myCustomElement.getElementById('id0').value).toBe(false)
    })

示例3)模拟该组件。

要使用@ testing-library检查按钮单击是否有动作:

import {render, fireEvent} from '@testing-library/svelte'
import {jest} from "@jest/globals";

it('testMyCustomElement_awesomeAction', async () => {
    const config = {booleanProp: true};
    const dom = render(MyCustomElement, config);

    const toggleButton = dom.getByLabelText('toggle-boolean-prop');
    await fireEvent.click(toggleButton);


    expect(config.booleanProp).toBe(false);
})

要捕获该元素,您需要一个aria标签来标识它:

<button aria-label="toggle-boolean-prop" class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>...</button>