【问题标题】:How do I test a simple Svelte shopping cart with Jest?如何使用 Jest 测试一个简单的 Svelte 购物车?
【发布时间】:2022-02-01 10:25:01
【问题描述】:

我有一个简单的 Svelte 产品目录,我需要使用 Jest 对其进行测试,但我不确定如何测试。该应用程序执行 fetch API 调用并呈现一些产品。当点击 + 按钮时,它们会被添加到购物车中,并且总价格会添加到页面底部显示的总价值中(只有价值,而不是购物车项目本身)。我需要测试是否为产品显示了正确的数据,并且当通过 + 按钮添加项目时,是否将正确的值添加到产品总数中。我必须使用 Jest,但如果需要,其他测试工具也可以。代码如下:

----App.svelte----


 <script>
    import { onMount } from 'svelte';
    import Product from './Product.svelte'
    import { total } from './stores.js'

  let products = [];

  onMount(async () => {
    const res = await fetch(`https://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline`);
    products = await res.json();
        products.forEach(function (element) {
        element.quantity = 5;
        });
    });
        
</script>

<h1>Products</h1>
    {#if products && products.length}
        <div class="photos">
        {#each products as product}
                <Product product={product} />
            {/each}
    </div>    
  {:else}
    <p>loading...</p>
  {/if}
   
<div>
    <h1>Total {$total.toFixed(2)}</h1>
</div>

<style>
    .photos {
        width: 100%;
        display: grid;
        grid-template-columns: repeat(5, 1fr);
        grid-gap: 8px;
    }

   
</style> 
---Product.svelte---


<script>
    import { total } from './stores.js';
    export let product;

    function increment(price) {
        $total = $total + price;
        product.quantity = product.quantity - 1;
    }

    function decrement(price) {
        $total = $total - price;
        product.quantity = product.quantity + 1;
    }

</script>

<figure>
    <img src={product.image_link} alt={product.name} />
    <figcaption>{product.name}</figcaption>
    <small
        >{product.price}<small />
        <h1>Quantity: {product.quantity}</h1>
        {#if product.quantity === 0}
        <button disabled>+</button>
        {:else}
        <button on:click={increment(parseFloat(product.price))}>+</button>
        {/if}

        {#if product.quantity === 5}
        <button disabled >-</button>
        {:else}
        <button on:click={decrement(parseFloat(product.price))}>-</button>
        {/if}
    </small>
</figure>

<style>
    figure,
    img {
        width: 100%;
        margin: 0;
    }
</style>

---stores.js---


import {writable} from 'svelte/store'

export const total = writable(0)


【问题讨论】:

    标签: unit-testing testing jestjs svelte


    【解决方案1】:

    一种方法是将业务逻辑放在 Svelte 组件之外,然后您可以在隔离 中对业务逻辑(可能是商店)进行单元测试,而无需测试整体Svelte 组件 + 后端。

    对于小型项目,我发现单元测试就足够了。但是当它更大时,您也可以使用 cypress 添加集成测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-11
      • 2023-03-25
      • 2014-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      相关资源
      最近更新 更多