Svelte with a Component iterating over an array of Objects - Error: {#each} only iterates over array-like objects

Viewed 49

Loving and Still learning Svelte by testing stuff. I have created a Component containing an Image (on the right) and an Article (on the left) ; the article section includes a header, a paragraph and button-like anchor(s) (it can be one or more according to the needs of the article) - that can be personalized (thanks to exported props).

As you will see below, I created buttonList = an array of objects (these being derived from a class ButtonModel), ButtonModel[] and iterate over it to show as many button-like anchors as needed (each with its href and its label):

<script lang="ts">
  import { Icon } from '@mylib/ui';
  class ButtonModel {
    href: string;
    label: string;
    constructor(href: string, label: string) {
      this.href = href;
      this.label = label;
    }
  }
  export let imgSrc: string;
  export let alt: string;
  export let articleTitle: string;
  export let articleContent: string;
  export let buttonList: ButtonModel[];
</script>

<div class="imagearticle">
  <img class="imagearticle__image" src={imgSrc} {alt} />
  <article class="imagearticle__article">
    <h1>{articleTitle}</h1>
    <p>{articleContent}</p>
    <div class="imagearticle__article__buttonGroup">
      {#each buttonList as buttonModel}
        <a class="button" href={buttonModel.href} role="button">
          <Icon name="chevron-right" />
          {buttonModel.label}
        </a>
      {/each}
    </div>
  </article>
</div>

When I use it in a page, it is correctly rendered in the browser:

<script lang="ts">
  import { _ } from 'svelte-i18n';
  import ArticleImage from '../lib/ImageArticle.svelte';
</script>

<main>
  <ArticleImage
    imgSrc="/images/forest.png"
    alt="Forest of cypress trees"
    articleTitle={$_('homepage.respect.title')}
    articleContent={$_('homepage.respect.p')}
    buttonList={[{ href: '/', label: $_('homepage.respect.btn') }]}
  />

  <ArticleImage
    imgSrc="/images/pairprogramming.png"
    alt="Two people pair programming in a shop"
    articleTitle={$_('homepage.inclusive.title')}
    articleContent={$_('homepage.inclusive.p')}
    buttonList={[
      { href: '/', label: $_('homepage.inclusive.btn') },
      { href: '/', label: $_('homepage.inclusive.contact') }
    ]}
  />
</main>

But when I run my test with Jest, I keep having the error message :
{#each} only iterates over array-like objects.

  1. Could you help me understand this error (when looping over an array of Objects] ?
  2. Any clues how to improve myself ? or the above code ?

Thanks

0 Answers
Related