Skip to content

Testing Documentation

This document provides detailed information about testing practices in the Elome Frontend project.

Testing Framework

The Elome Frontend project uses Vitest as its testing framework, along with Vue Test Utils for testing Vue components. The testing configuration is defined in vitest.config.ts.

Test Types

The project includes several types of tests:

Unit Tests

Unit tests focus on testing individual functions, methods, or small components in isolation. They are typically fast and help ensure that specific pieces of code work as expected.

Location: tests/unit/

Example:

// tests/unit/composables/usePriceFormatter.spec.ts
import { describe, it, expect } from 'vitest';
import { usePriceFormatter } from '~/composables/usePriceFormatter';

describe('usePriceFormatter', () => {
  it('formats price with default options', () => {
    const { formatPrice } = usePriceFormatter();
    expect(formatPrice(100)).toBe('100,00 kr');
  });

  it('formats price with custom decimals', () => {
    const { formatPrice } = usePriceFormatter();
    expect(formatPrice(100, { decimals: 0 })).toBe('100 kr');
  });
});

Component Tests

Component tests verify that Vue components render correctly and behave as expected when interacted with. They use Vue Test Utils to mount components and simulate user interactions.

Location: tests/components/

Example:

// tests/components/cart/FreeShippingNotice.spec.ts
import { describe, it, expect, vi } from 'vitest';
import { mount } from '@vue/test-utils';
import FreeShippingNotice from '~/components/cart/FreeShippingNotice.vue';

// Mock the composables
vi.mock('~/composables/useCartHelpers', () => ({
  useCartHelpers: () => ({
    freeShippingUnlocked: ref(false),
    freeShippingEnabled: ref(true),
    amountUntilFreeShipping: ref(50),
    totalQuantity: ref(2)
  })
}));

describe('FreeShippingNotice', () => {
  it('renders when free shipping is enabled and cart has items', () => {
    const wrapper = mount(FreeShippingNotice);
    expect(wrapper.isVisible()).toBe(true);
  });

  it('shows the correct message when free shipping is not unlocked', () => {
    const wrapper = mount(FreeShippingNotice);
    expect(wrapper.text()).toContain('50');
  });
});

Integration Tests

Integration tests verify that multiple components or systems work together correctly. They test the interaction between different parts of the application.

Location: tests/integration/

Example:

// tests/integration/cart-checkout-flow.spec.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { mount } from '@vue/test-utils';
import { createTestingPinia } from '@pinia/testing';
import CartPage from '~/pages/cart.vue';

describe('Cart to Checkout Flow', () => {
  let wrapper;

  beforeEach(() => {
    // Create a test Pinia instance
    const pinia = createTestingPinia({
      initialState: {
        cart: {
          cart: {
            contents: {
              itemCount: 2,
              nodes: [/* mock cart items */]
            },
            rawTotal: 100
          },
          isShowingCart: true
        }
      }
    });

    // Mount the component with the test store
    wrapper = mount(CartPage, {
      global: {
        plugins: [pinia]
      }
    });
  });

  it('displays the correct number of cart items', () => {
    expect(wrapper.findAll('.cart-item')).toHaveLength(2);
  });

  it('shows the correct cart total', () => {
    expect(wrapper.find('.cart-total').text()).toContain('100');
  });
});

Running Tests

Running All Tests

To run all tests:

bun run test

Running Tests in Watch Mode

For development, you can run tests in watch mode, which will automatically re-run tests when files change:

bun run test:watch

Running Tests with Coverage

To generate a test coverage report:

bun run test:coverage

This will generate a coverage report in the coverage/ directory.

Writing Tests

Test Structure

Tests should follow this general structure:

  1. Import necessary dependencies
  2. Set up mocks and stubs (if needed)
  3. Define test suite with describe
  4. Define individual tests with it or test
  5. Set up test environment (e.g., mount components, create stores)
  6. Perform actions (if testing behavior)
  7. Assert expected outcomes

Mocking

Vitest provides several ways to mock dependencies:

Function Mocks

import { vi } from 'vitest';

// Mock a function
const mockFn = vi.fn().mockReturnValue('mocked value');

// Spy on a method
const spy = vi.spyOn(object, 'method').mockImplementation(() => 'mocked');

Module Mocks

import { vi } from 'vitest';

// Mock a module
vi.mock('~/composables/useHelpers', () => ({
  useHelpers: () => ({
    logGQLError: vi.fn(),
    clearAllCookies: vi.fn()
  })
}));

Testing Asynchronous Code

For testing asynchronous code, use async/await:

it('fetches data asynchronously', async () => {
  const result = await fetchData();
  expect(result).toEqual({ data: 'value' });
});

Testing Vue Components

When testing Vue components:

  1. Use mount for full rendering or shallowMount for shallow rendering
  2. Use wrapper.find and wrapper.findAll to select elements
  3. Use wrapper.trigger to simulate user events
  4. Use await nextTick() after actions that cause Vue to update
import { mount } from '@vue/test-utils';
import MyComponent from '~/components/MyComponent.vue';

const wrapper = mount(MyComponent, {
  props: {
    message: 'Hello'
  }
});

// Find elements
const button = wrapper.find('button');
const text = wrapper.find('.message');

// Check content
expect(text.text()).toBe('Hello');

// Trigger events
await button.trigger('click');

// Check updated state
expect(wrapper.emitted().click).toBeTruthy();

Test Best Practices

  1. Test in isolation: Mock dependencies to isolate the code being tested
  2. Test behavior, not implementation: Focus on what the code does, not how it does it
  3. Keep tests simple: Each test should verify one specific behavior
  4. Use descriptive test names: Test names should clearly describe what is being tested
  5. Arrange, Act, Assert: Structure tests with setup, action, and verification phases
  6. Don't test third-party code: Focus on testing your own code, not libraries
  7. Maintain test independence: Tests should not depend on each other
  8. Clean up after tests: Reset state between tests to prevent interference

Continuous Integration

The project uses GitHub Actions for continuous integration. Tests are automatically run on pull requests and pushes to the main branch.

The CI workflow is defined in .github/workflows/ci.yml and includes:

  1. Linting: Checking code style with ESLint
  2. Type checking: Verifying TypeScript types
  3. Unit tests: Running all tests
  4. Coverage report: Generating and uploading test coverage reports

Troubleshooting Common Test Issues

Tests Failing in CI but Passing Locally

  • Check for environment differences
  • Ensure all dependencies are properly mocked
  • Look for timing issues in asynchronous tests

Slow Tests

  • Minimize DOM operations
  • Use shallowMount instead of mount when possible
  • Mock expensive operations
  • Run only relevant tests during development

Flaky Tests

  • Avoid timing dependencies
  • Ensure proper cleanup between tests
  • Use explicit waits instead of timeouts
  • Add more specific assertions