Within my src/lib/apis directory I have a file named data.ts which contains the below code:
export async function getData(searchInput: string) {return fetch('https://dummyjson.com/products', { method: 'get' }).then((res) => res.json());}
within my src/lib/components directory I have a svelte component named ClientSearch.svelte with the following code:
<script lang="ts">import { getData } from '../apis/data';let searchInput = '';let data: { [key: string]: any };const handleSearch = async () => {getData(searchInput).then((res) => { data = res; }); };</script><div><input type="text" placeholder="text search" bind:value={searchInput} on:keyup={handleSearch} />{#if data?.products?.length}{data.products[0].title}{/if}</div>
how can I test this ClientSearch.svelte component using Vitest? How can I write unit test to test the functionality that when a key is press that API is called and data that is fetched is displayed on the screen (I thought of mocking the api but failed to do so).
import { describe, expect, it, vi } from 'vitest';import { render, screen, fireEvent, getByText } from '@testing-library/svelte'; import ClientSearch from '$lib/components/ClientSearch.svelte'; import { getData } from '../lib/apis/data';vi.mock('../apis/data', () => ({ getData: vi.fn(() => Promise.resolve({ products: [{ title: 'Test Product' }] })) }));describe('ClientSearch.svelte', async () => { it('should display the first product title when a search is made', async () => { const { getByPlaceholderText, queryByText } = render(ClientSearch); const input = getByPlaceholderText('text search'); expect(input).toBeInTheDocument(); await fireEvent.keyUp(input, { target: { value: 'example' } }); console.log(queryByText('Test Product'));});});
I tried this out but it's printing null on console.