Testing a Svelte Component with Unit Tests { #conditionals }

Test Procedure

Instructions

To begin, execute the following bash command:

mkdir example && cd example && mkdir src && touch jest.config.js && pnpm init && pnpm i @jest/globals @testing-library/svelte jest jest-environment-jsdom svelte svelte-jester -D && cd src && touch Example.test.js && touch Example.svelte && cd ..

Add to package.json

{
  "type": "module",
  "scripts": {
    "test": "NODE_OPTIONS=--experimental-vm-modules pnpm jest"
  }
}

Setting up jest.config.js

/** @type { import('jest').Config } */
const config = { 
  clearMocks: true, 
  collectCoverage: true, 
  coverageDirectory: 'coverage', 
  coverageProvider: 'v8', 
  injectGlobals: false, 
  testEnvironment: 'jest-environment-jsdom', 
  moduleFileExtensions: ['js', 'svelte'], 
  extensionsToTreatAsEsm: ['.svelte'], 
  transform: { '^.+\.svelte$': 'svelte-jester' }, 
}

export default config

Content of Example.svelte

<script>
  let value

  function setValue (e) {
    value = e.target.value
  }
</script>


<textarea on:input={ setValue }></textarea>
{ #if value }
  { value }
{ /if }

Code for Example.test.js

import Example from './Example.svelte'
import { describe, test, expect } from '@jest/globals'
import { render, fireEvent, screen } from '@testing-library/svelte'


describe('Testing Example.svelte Component', () => {
  test('Functionality Check', async () => {
    const value = 'hello world'

    expect(screen.queryByText(value)).toBeFalsy() // Pre-render component => No visible text in DOM

    const { container } = render(Example) // Render component
    const textarea = container.querySelector('textarea')
    expect(screen.queryByText(value)).toBeFalsy() // Value still not present in DOM

    await fireEvent.input(textarea, { target: { value } }) // Add value to textarea
    expect(screen.queryByText(value)).toBeTruthy() // Value should be visible in DOM now

    await fireEvent.input(textarea, { target: { value: '' } }) // Remove value from textarea
    expect(screen.queryByText(value)).toBeFalsy() // Value should no longer be present in DOM
  })
})

Evaluation Results

  • All tests have passed successfully
  • The issue with an uncovered line #11 in Example.svelte has been identified.
 PASS  src/Example.test.js
  Example.svelte
    ✓ Functionality Check (26 ms)

----------------|---------|----------|---------|---------|-------------------
File            | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------------|---------|----------|---------|---------|-------------------
All files       |     100 |        0 |     100 |     100 |                   
 Example.svelte |     100 |        0 |     100 |     100 | 11                
----------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.113 s

Initiating Line 11 Test

Answer №1

It appears that the coverage output is inaccurate, which is a common issue when using svelte and jest together.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

Converting numbers to strings based on locale in React Native

I have a quantity that, when using the amount.toFixed() function, produces the string "100.00". I would like this result to be formatted according to the specific locale. For example, in Italian the desired output is 100,00, while in English it should be ...

Struggling to make a basic JavaScript prompt function as expected

<html> <title>UniqueTitle</title> <head> <link rel="stylesheet" type="text/css" href="style.css" > <script type="text/javascript"> function modifyDates() { var dates = pr ...

Transforming an unconventional date format into a proper date representation

I have a spreadsheet with over 100,000 dates stored in the following format: Thursday 29th of October 2015 01:06:21 PM Converting these dates into a usable format is proving to be a challenge. Whether it's YYYY/MM/DD or any other standard format, I ...

Chrome full screen mode can be toggled on websites after ajax data has loaded

I am currently experiencing a frustrating issue with Chrome on my webpage. The pagination feature loads content via an ajax call at: Whenever I click on the 2nd, 3rd, or subsequent tab in the pagination, the load process occurs but then suddenly jumps int ...

including identical item in the array

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css"> <body> <script> var app = angul ...

The persistentFilter in the Tabulator is failing to verify for the headerFilterEmptyCheck

Using Tabulator version 4.4.3 When filtering the checkbox in the usual way, everything works fine. If I set a filtered checkbox to true on a column, it functions correctly: headerFilterEmptyCheck: function (value) { return !value; }, Howev ...

Caution: Updating a component is not possible during the rendering of another component. ReactJS

I am encountering an error in my ReactHooks/Typescript application with a Navigation component that renders a PatientInfo component. The PatientInfo component is conditionally rendered based on the props it receives, determined by a searchbox in another ch ...

Troubles arise when attempting to utilize yarn for my projects

Whenever I enter the command yarn start in the terminal, I get this output: yarn run v1.22.4 $ react-scripts start 'react-scripts' is not recognized as an internal or external command, operable program or batch file. error Command fai ...

Endless asynchronous loops with setInterval()

My nodejs application requires multiple infinite loops that call asynchronous functions. I was contemplating the following approach: async function process1() { ...perform some asynchronous tasks... } async function process2() { ...perform some as ...

How to dynamically update form select options using Zend Framework 2 (2.3) and AJAX

I'm facing an issue with concatenating 3 dynamic selects - state, country, city - using an ajax request. It seems more complex without zf2! The function works fine when $idState is manually set within stateCountryCityAction (e.g. $idState = 1;), but d ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Using v-model with variables in Vue

In my form, I am encountering an issue with a textarea field when inserting a value from the database (using Laravel 10 and Inertia) where it is not being displayed. However, in other instances, the value appears as expected. It seems that there is a confl ...

Using React Refs to Trigger the video.play() Method - A Step-by-Step Guide

Is there a way to use a ref in order to trigger video.play()? Currently encountering an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function Take a look at my component: import React from 'react'; import s ...

Issue with idangero.us swiper: resizing problem occurs when image exceeds window size

Having an issue where resizing my window causes the image to become larger than anticipated. As a result, the current image is partially cropped on the left side while the previous image starts to show through. Here's a description of what's happ ...

In iOS devices, the Ionic framework restricts the ability to open links in a new tab using the ng-href attribute

In my quest for mobile functionality, I'm aiming to implement a feature on devices where tapping will open 'codepen.io' (triggered by ng-click), and tap and hold will display a context menu with the option to 'Open In New Tab', red ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

Retrieve Vuejs template by either module or ID

In my .Vue file, I have defined a template along with its subcomponents with the intention of allowing customers to override this template without needing to modify any javascript code. If there exists an element with id="search-result", then that element ...

Encountering a ReferenceError while debugging MongoDB: The console object is undefined

Using a js file within mongodb, I implemented a code snippet containing a console.log expression for debugging purposes: use test; db.city.find().snapshot().forEach(function(city){ var Pos = city.Pos; if (Pos) { longLat = Pos.split(" ...

What is the best way to retrieve and utilize this JSON information with D3?

Understanding how to load JSON in D3 is crucial for working with data visualization. The process involves using the following code snippet without encountering any errors: d3.json("sample_data/unique_items.json", function(json) { // do something }); Af ...