0

问题:如何使用 jest 测试访问一个苗条组件的 props。例如,如果 svelte 组件如下所示:

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>
4

1 回答 1

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-label 来识别它:

<button aria-label="toggle-boolean-prop" class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>...</button>
于 2020-06-19T11:49:35.013 回答