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:
Running Tests in Watch Mode¶
For development, you can run tests in watch mode, which will automatically re-run tests when files change:
Running Tests with Coverage¶
To generate a test coverage report:
This will generate a coverage report in the coverage/ directory.
Writing Tests¶
Test Structure¶
Tests should follow this general structure:
- Import necessary dependencies
- Set up mocks and stubs (if needed)
- Define test suite with
describe - Define individual tests with
itortest - Set up test environment (e.g., mount components, create stores)
- Perform actions (if testing behavior)
- 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:
- Use
mountfor full rendering orshallowMountfor shallow rendering - Use
wrapper.findandwrapper.findAllto select elements - Use
wrapper.triggerto simulate user events - 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¶
- Test in isolation: Mock dependencies to isolate the code being tested
- Test behavior, not implementation: Focus on what the code does, not how it does it
- Keep tests simple: Each test should verify one specific behavior
- Use descriptive test names: Test names should clearly describe what is being tested
- Arrange, Act, Assert: Structure tests with setup, action, and verification phases
- Don't test third-party code: Focus on testing your own code, not libraries
- Maintain test independence: Tests should not depend on each other
- 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:
- Linting: Checking code style with ESLint
- Type checking: Verifying TypeScript types
- Unit tests: Running all tests
- 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
shallowMountinstead ofmountwhen 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