Bird
Raised Fist0
Svelteframework~20 mins

Unit testing logic in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Svelte Unit Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Svelte component test?
Given the following Svelte component and its test, what will the test output?
Svelte
/* Component: Counter.svelte */
<script>
  export let start = 0;
  let count = start;
  function increment() {
    count += 1;
  }
</script>
<button on:click={increment} aria-label="Increment">Count: {count}</button>

/* Test file: Counter.test.js */
import { render, fireEvent } from '@testing-library/svelte';
import Counter from './Counter.svelte';

test('increments count on click', async () => {
  const { getByRole } = render(Counter, { start: 5 });
  const button = getByRole('button', { name: /increment/i });
  expect(button.textContent).toBe('Count: 5');
  await fireEvent.click(button);
  expect(button.textContent).toBe('Count: 6');
});
ATest throws a runtime error due to missing event handler.
BTest fails because the button text does not update after click.
CTest fails because initial count is 0 instead of 5.
DTest passes successfully with count incrementing from 5 to 6.
Attempts:
2 left
💡 Hint
Remember that Svelte updates reactive variables and the DOM automatically after events.
❓ state_output
intermediate
2:00remaining
What is the value of 'message' after this test runs?
Consider this Svelte component and its test. What will be the final value of the 'message' variable after the test completes?
Svelte
<script>
  import { writable } from 'svelte/store';
  export const message = writable('Hello');
  export function updateMessage(newMsg) {
    message.set(newMsg);
  }
</script>

// Test file
import { message, updateMessage } from './MessageStore.js';

test('updates message store', () => {
  let current;
  const unsubscribe = message.subscribe(value => current = value);
  expect(current).toBe('Hello');
  updateMessage('Hi there');
  expect(current).toBe('Hi there');
  unsubscribe();
});
A'Hello'
B'Hi there'
Cundefined
Dnull
Attempts:
2 left
💡 Hint
Svelte stores update subscribers immediately when set is called.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error in this Svelte test?
Identify which test code snippet will cause a syntax error when testing a Svelte component.
Svelte
import { render } from '@testing-library/svelte';
import MyComponent from './MyComponent.svelte';
A;)} ;)(tnemucoDehTnIeBot.))'olleH'(txeTyBteg(tcepxe ;)tnenopmoCyM(redner = } txeTyBteg { tsnoc { >= )( ,'yltcerroc sredner'(tset
Btest('renders correctly', () => { const { getByText } = render(MyComponent); expect(getByText('Hello')).toBeInTheDocument() });
Ctest('renders correctly', () => { const { getByText } = render(MyComponent); expect(getByText('Hello')).toBeInTheDocument(); });
Dest('renders correctly', () => { const { getByText } = render(MyComponent); expect(getByText('Hello')).toBeInTheDocument(); });
Attempts:
2 left
💡 Hint
Check the syntax of the test function declaration carefully.
🔧 Debug
advanced
2:00remaining
Why does this Svelte test fail to detect a button click?
This test tries to check if a button click updates text, but it fails. Why?
Svelte
<script>
  let clicked = false;
  function handleClick() {
    clicked = true;
  }
</script>
<button on:click={handleClick}>Click me</button>
<p>{clicked ? 'Clicked!' : 'Not clicked'}</p>

// Test file
import { render, fireEvent } from '@testing-library/svelte';
import ClickComponent from './ClickComponent.svelte';

test('button click updates text', async () => {
  const { getByText } = render(ClickComponent);
  const button = getByText('Click me');
  expect(getByText('Not clicked')).toBeInTheDocument();
  await fireEvent.click(button);
  expect(getByText('Clicked!')).toBeInTheDocument();
});
AThe 'clicked' variable is not reactive, so Svelte does not update the DOM after click.
BThe test does not wait for the DOM update after the click event.
CThe button does not have an on:click event handler attached.
DThe test uses getByText incorrectly and cannot find the button.
Attempts:
2 left
💡 Hint
In Svelte, variables must be reactive to trigger DOM updates.
🧠 Conceptual
expert
3:00remaining
Which statement best explains why mocking a Svelte store is important in unit tests?
When unit testing a Svelte component that uses a writable store, why is it important to mock the store instead of using the real one?
AMocking the store isolates the component test from external state changes, ensuring predictable and fast tests.
BUsing the real store always causes runtime errors in tests due to Svelte internals.
CMocking the store is unnecessary because Svelte automatically resets stores between tests.
DThe real store cannot be imported in test files due to module resolution issues.
Attempts:
2 left
💡 Hint
Think about test isolation and control over data during tests.

Practice

(1/5)
1. What is the main purpose of unit testing in Svelte applications?
easy
A. To write HTML templates
B. To style components with CSS
C. To check small parts of code for errors early
D. To deploy the app to production

Solution

  1. Step 1: Understand unit testing purpose

    Unit testing focuses on testing small, isolated parts of code to find bugs early.
  2. Step 2: Compare options to unit testing goal

    Only To check small parts of code for errors early describes checking small code parts for errors early, which matches unit testing.
  3. Final Answer:

    To check small parts of code for errors early -> Option C
  4. Quick Check:

    Unit testing = check small code parts early [OK]
Hint: Unit tests check small code parts, not styling or deployment [OK]
Common Mistakes:
  • Confusing unit testing with styling or deployment
  • Thinking unit tests write HTML templates
  • Assuming unit tests run only in production
2. Which of the following is the correct syntax to define a test case in Svelte using Vitest or Jest?
easy
A. test('test case') { /* test code */ }
B. describe 'test group' { it 'test case' { /* test code */ } }
C. it 'test case' => { /* test code */ }
D. describe('test group', () => { it('test case', () => { /* test code */ }) })

Solution

  1. Step 1: Recall correct test syntax

    In Vitest/Jest, tests use describe() and it() functions with arrow functions.
  2. Step 2: Check each option's syntax

    describe('test group', () => { it('test case', () => { /* test code */ }) }) uses correct parentheses and arrow functions. Others miss parentheses or use wrong syntax.
  3. Final Answer:

    describe('test group', () => { it('test case', () => { /* test code */ }) }) -> Option D
  4. Quick Check:

    describe and it with arrow functions = correct syntax [OK]
Hint: Use parentheses and arrow functions with describe and it [OK]
Common Mistakes:
  • Omitting parentheses around function arguments
  • Using wrong arrow function syntax
  • Confusing test and it keywords
3. Given this test code snippet, what will be the test result?
describe('sum function', () => {
  it('adds two numbers', () => {
    const sum = (a, b) => a + b;
    expect(sum(2, 3)).toBe(5);
  });
});
medium
A. The test will pass because 2 + 3 equals 5
B. The test will fail because sum is not defined
C. The test will fail because toBe is not a function
D. The test will throw a syntax error

Solution

  1. Step 1: Analyze the sum function and test

    The sum function adds two numbers correctly. The test checks if sum(2, 3) equals 5.
  2. Step 2: Evaluate the expect statement

    expect(sum(2, 3)).toBe(5) compares 5 to 5, which is true, so the test passes.
  3. Final Answer:

    The test will pass because 2 + 3 equals 5 -> Option A
  4. Quick Check:

    sum(2,3) = 5, expect toBe(5) passes [OK]
Hint: Check function output matches expected value exactly [OK]
Common Mistakes:
  • Assuming sum is undefined
  • Confusing toBe with other matchers
  • Thinking syntax error occurs here
4. Identify the error in this Svelte unit test code:
describe('multiply function', () => {
  it('multiplies two numbers', () => {
    const multiply = (a, b) => a * b
    expect(multiply(2, 3)).toBe(6)
  }
});
medium
A. Missing closing parenthesis for the it block
B. multiply function is not defined
C. toBe matcher is used incorrectly
D. describe block is missing a callback function

Solution

  1. Step 1: Check syntax of it block

    The it block starts with a parenthesis but lacks a closing parenthesis before the closing brace.
  2. Step 2: Verify other parts

    multiply is defined correctly, toBe is used properly, and describe has a callback function.
  3. Final Answer:

    Missing closing parenthesis for the it block -> Option A
  4. Quick Check:

    Syntax error due to missing parenthesis [OK]
Hint: Count opening and closing parentheses carefully [OK]
Common Mistakes:
  • Ignoring missing parentheses errors
  • Thinking multiply is undefined
  • Assuming toBe usage is wrong
5. You want to write a unit test in Svelte that checks if a function returns the correct value only when the input is positive. Which test logic correctly implements this condition?
function checkPositive(n) {
  return n > 0 ? 'positive' : 'not positive';
}
hard
A. expect(checkPositive(0)).toBe('positive'); expect(checkPositive(5)).toBe('not positive');
B. expect(checkPositive(5)).toBe('positive'); expect(checkPositive(-1)).toBe('not positive');
C. expect(checkPositive(-5)).toBe('positive'); expect(checkPositive(5)).toBe('positive');
D. expect(checkPositive(5)).toBe('not positive'); expect(checkPositive(-1)).toBe('positive');

Solution

  1. Step 1: Understand function behavior

    checkPositive returns 'positive' if input > 0, else 'not positive'.
  2. Step 2: Match test expectations to function logic

    expect(checkPositive(5)).toBe('positive'); expect(checkPositive(-1)).toBe('not positive'); tests positive input 5 returns 'positive' and negative input -1 returns 'not positive', matching function logic.
  3. Final Answer:

    expect(checkPositive(5)).toBe('positive'); expect(checkPositive(-1)).toBe('not positive'); -> Option B
  4. Quick Check:

    Test matches function output for positive and negative inputs [OK]
Hint: Test both positive and negative inputs to cover conditions [OK]
Common Mistakes:
  • Testing zero as positive incorrectly
  • Swapping expected results for inputs
  • Testing only one input case
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard