阿里云主机折上折
  • 微信号
Current Site:Index > Test toolchain configuration

Test toolchain configuration

Author:Chuan Chen 阅读数:37232人阅读 分类: 构建工具

Testing Toolchain Configuration

The testing toolchain configuration for Vite.js directly impacts development efficiency and code quality. A well-configured setup enables seamless integration of unit testing, component testing, and end-to-end testing into the development workflow.

Unit Testing Configuration

Jest is a common unit testing framework. Install the required dependencies in a Vite project:

npm install --save-dev jest @types/jest @vue/test-utils

Create a jest.config.js file:

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  transform: {
    '^.+\\.vue$': '@vue/vue3-jest',
    '^.+\\.ts$': 'ts-jest'
  }
}

Example test file src/utils/math.test.ts:

import { add } from '@/utils/math'

describe('math utilities', () => {
  it('adds two numbers correctly', () => {
    expect(add(2, 3)).toBe(5)
  })
})

Component Testing Configuration

For Vue component testing, additional configuration is required:

npm install --save-dev @testing-library/vue

Configure vite.config.js to support testing:

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom'
  }
})

Component test example src/components/Button.test.ts:

import { render } from '@testing-library/vue'
import Button from './Button.vue'

test('renders button with correct text', () => {
  const { getByText } = render(Button, {
    props: {
      label: 'Click me'
    }
  })
  
  expect(getByText('Click me')).toBeInTheDocument()
})

End-to-End Testing Configuration

Cypress is suitable for end-to-end testing. Installation command:

npm install --save-dev cypress

Create cypress.config.js:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:5173',
    setupNodeEvents(on, config) {
      // Implement plugins
    }
  }
})

Test example cypress/e2e/home.cy.js:

describe('Home Page', () => {
  it('successfully loads', () => {
    cy.visit('/')
    cy.contains('Welcome to Vite App').should('be.visible')
  })
})

Test Coverage Configuration

Add coverage configuration to jest.config.js:

module.exports = {
  collectCoverage: true,
  coverageDirectory: 'coverage',
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80
    }
  }
}

Test Environment Variable Handling

Create a .env.test file:

VITE_API_BASE=http://test.api.example.com

Modify vite.config.js:

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  
  return {
    define: {
      'process.env': env
    }
  }
})

Test and Build Integration

Add scripts to package.json:

{
  "scripts": {
    "test:unit": "jest",
    "test:e2e": "cypress run",
    "test": "run-p test:unit test:e2e"
  }
}

Test Toolchain Optimization

Use the vite-plugin-test plugin to enhance testing experience:

import test from 'vite-plugin-test'

export default defineConfig({
  plugins: [
    test({
      include: ['**/*.{test,spec}.{js,ts}'],
      globals: true
    })
  ]
})

Test Data Mocking

Create mock service:

// src/mocks/handlers.js
import { rest } from 'msw'

export const handlers = [
  rest.get('/api/user', (req, res, ctx) => {
    return res(
      ctx.json({
        id: 1,
        name: 'Test User'
      })
    )
  })
]

Configure test environment to use mocks:

// src/setupTests.js
import { setupServer } from 'msw/node'
import { handlers } from './mocks/handlers'

const server = setupServer(...handlers)

beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())

Test Type Checking

Add test type support in tsconfig.json:

{
  "compilerOptions": {
    "types": ["jest", "node"]
  }
}

Test Performance Optimization

Parallel test execution:

// jest.config.js
module.exports = {
  maxWorkers: '50%',
  testEnvironment: 'jsdom'
}

For large test suites, use jest-runner-groups:

{
  "scripts": {
    "test:unit:fast": "jest --group=fast",
    "test:unit:slow": "jest --group=slow"
  }
}

Test Report Generation

Configure Jest to generate HTML reports:

module.exports = {
  reporters: [
    'default',
    ['jest-html-reporters', {
      publicPath: './test-reports',
      filename: 'report.html'
    }]
  ]
}

Cypress report configuration:

// cypress.config.js
module.exports = defineConfig({
  reporter: 'junit',
  reporterOptions: {
    mochaFile: 'cypress/results/output.xml'
  }
})

Test and CI/CD Integration

GitHub Actions configuration example .github/workflows/test.yml:

name: Test
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 16
      - run: npm ci
      - run: npm run test:unit
      - run: npm run test:e2e

Test Debugging Configuration

VS Code debugging configuration .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Jest Tests",
      "program": "${workspaceFolder}/node_modules/jest/bin/jest",
      "args": ["--runInBand"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]
}

Test Snapshot Management

Jest snapshot test example:

import { render } from '@testing-library/vue'
import Component from './Component.vue'

test('renders correctly', () => {
  const { container } = render(Component)
  expect(container).toMatchSnapshot()
})

Command to update snapshots:

npm test -- -u

Test Toolchain Extension

Integrate Storybook testing:

npx storybook init

Configure Storybook testing plugin .storybook/main.js:

module.exports = {
  stories: ['../src/**/*.stories.@(js|ts)'],
  addons: [
    '@storybook/addon-actions',
    '@storybook/addon-interactions'
  ],
  framework: '@storybook/vue3'
}

Testing and State Management

Example of testing a Pinia store:

import { setActivePinia, createPinia } from 'pinia'
import { useCounterStore } from '@/stores/counter'

describe('Counter Store', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
  })

  it('increments count', () => {
    const counter = useCounterStore()
    counter.increment()
    expect(counter.count).toBe(1)
  })
})

Testing Routing

Example of testing Vue Router:

import { mount } from '@vue/test-utils'
import { createRouter, createWebHistory } from 'vue-router'
import Component from './Component.vue'

const router = createRouter({
  history: createWebHistory(),
  routes: [{ path: '/', component: Component }]
})

test('navigates to home', async () => {
  const wrapper = mount(Component, {
    global: {
      plugins: [router]
    }
  })
  
  await wrapper.find('a').trigger('click')
  expect(wrapper.vm.$route.path).toBe('/')
})

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.