阿里云主机折上折
  • 微信号
Current Site:Index > Debugging and testing tools for mini-programs

Debugging and testing tools for mini-programs

Author:Chuan Chen 阅读数:47515人阅读 分类: 微信小程序

Basic Functions of Mini Program Debugging Tools

The WeChat Developer Tools come with comprehensive debugging features, mainly including the following core modules:

  1. Console Panel: Displays runtime logs, error messages, and debug output
  2. Sources Panel: Views and debugs source code
  3. Network Panel: Monitors network requests
  4. Storage Panel: Views and manages local storage data
  5. AppData Panel: Real-time viewing and modification of page data
// Example: Debugging in the Console Panel
console.log('Current page path:', getCurrentPages()[0].route)
wx.getSystemInfo({
  success(res) {
    console.log('System info:', res)
  }
})

Practical Tips for Real-Device Debugging

Real-device debugging is an indispensable part of mini-program development. Key points to note include:

  • Use the Remote Debugging feature to connect the developer tools to the phone
  • Scanning a QR code is required to enable debug mode on the phone
  • API behaviors in real-device environments may differ from those in simulators

Common issue resolutions:

  1. Blank screen on real devices: Check the domain whitelist and HTTPS configuration
  2. Style discrepancies: Use rpx units to adapt to different screens
  3. API compatibility: Use wx.canIUse to determine API availability
// Example of checking API availability
if(wx.canIUse('getUserProfile')) {
  wx.getUserProfile({
    desc: 'For improving member profile',
    success(res) {
      console.log('User info:', res.userInfo)
    }
  })
} else {
  console.warn('Current base library version does not support getUserProfile')
}

Automated Testing Solutions

Mini-program automated testing is mainly divided into three types:

Unit Testing

Use testing frameworks like Jest to test utility functions and component logic:

// utils.test.js
const { formatPrice } = require('./utils')

test('Format price display', () => {
  expect(formatPrice(100)).toBe('¥100.00')
  expect(formatPrice(1234.5)).toBe('¥1,234.50')
})

E2E Testing

Use miniprogram-automator for end-to-end testing:

const automator = require('miniprogram-automator')

describe('Shopping Cart Test', () => {
  let miniProgram
  beforeAll(async () => {
    miniProgram = await automator.launch({
      projectPath: 'path/to/project'
    })
  })

  it('Should add items correctly', async () => {
    const page = await miniProgram.reLaunch('/pages/cart/index')
    await page.waitFor(500)
    const addBtn = await page.$('.add-btn')
    await addBtn.tap()
    const count = await page.data('cartCount')
    expect(count).toBe(1)
  })
})

Cloud Testing Services

The official WeChat cloud testing service covers:

  • Testing on different device models
  • Performance testing
  • Compatibility testing

Performance Analysis and Optimization Tools

The Audits panel in the developer tools provides comprehensive performance analysis:

  1. Launch Performance: Monitors cold and hot start times of the mini-program
  2. Runtime Performance: Analyzes the frequency and data volume of setData calls
  3. Memory Usage: Detects memory leaks

Optimization recommendations:

  • Avoid frequent setData calls and merge data updates
  • Use custom components to reduce update scope
  • Use CDN for image resources and compress them appropriately
// Bad practice
this.setData({ a: 1 })
this.setData({ b: 2 })

// Recommended practice
this.setData({
  a: 1,
  b: 2
})

Exception Monitoring and Reporting

A robust error monitoring mechanism is needed for production environments:

  1. Error Capture:
// app.js
App({
  onError(err) {
    wx.request({
      url: 'https://api.example.com/error',
      data: {
        msg: err.message,
        stack: err.stack
      }
    })
  }
})
  1. API Call Monitoring:
const originalRequest = wx.request
wx.request = function(options) {
  const start = Date.now()
  return originalRequest({
    ...options,
    success(res) {
      reportApiPerformance(options.url, Date.now() - start)
      options.success && options.success(res)
    },
    fail(err) {
      reportApiError(options.url, err)
      options.fail && options.fail(err)
    }
  })
}

Key Points of Security Testing

Mini-program security testing should focus on:

  1. Sensitive Information Leakage: Check if the code contains sensitive information like API keys
  2. XSS Protection: Ensure all dynamic content is securely processed
  3. Permission Control: Verify that permission checks for each interface are complete
// Insecure practice
Page({
  onLoad(query) {
    this.setData({
      content: query.html // Directly rendering user input
    })
  }
})

// Secure practice
const { html } = require('./security.js')

Page({
  onLoad(query) {
    this.setData({
      content: html.sanitize(query.html) // Filtering dangerous tags
    })
  }
})

Continuous Integration Practices

Integrate mini-program testing into the CI process:

  1. Code Linting: Use ESLint to ensure consistent code style
  2. Automated Builds: Use CI tools to automatically package and upload alpha versions
  3. Automated Testing: Trigger test suites on every commit

Example GitLab CI configuration:

stages:
  - test
  - deploy

unit_test:
  stage: test
  script:
    - npm install
    - npm test

deploy_alpha:
  stage: deploy
  script:
    - npm run build
    - ./upload.js --env alpha
  only:
    - master

Multi-Scenario Testing Strategies

Adopt different testing methods for different scenarios:

  1. Payment Process: Use sandbox environments to test the complete payment flow
  2. User Authorization: Simulate various authorization rejection scenarios
  3. Network Exceptions: Test performance under weak or disconnected network conditions
// Simulating weak network environment testing
Page({
  onLoad() {
    // In developer tools, set Network to Slow 3G
    this.loadData()
  },
  
  loadData() {
    wx.showLoading({ title: 'Loading' })
    wx.request({
      url: 'https://api.example.com/data',
      success: (res) => {
        this.setData({ list: res.data })
      },
      fail: (err) => {
        wx.showToast({ title: 'Load failed', icon: 'none' })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
})

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.