【发布时间】: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