Debugging and testing tools for mini-programs
Basic Functions of Mini Program Debugging Tools
The WeChat Developer Tools come with comprehensive debugging features, mainly including the following core modules:
- Console Panel: Displays runtime logs, error messages, and debug output
- Sources Panel: Views and debugs source code
- Network Panel: Monitors network requests
- Storage Panel: Views and manages local storage data
- 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:
- Blank screen on real devices: Check the domain whitelist and HTTPS configuration
- Style discrepancies: Use
rpx
units to adapt to different screens - 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:
- Launch Performance: Monitors cold and hot start times of the mini-program
- Runtime Performance: Analyzes the frequency and data volume of
setData
calls - 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:
- Error Capture:
// app.js
App({
onError(err) {
wx.request({
url: 'https://api.example.com/error',
data: {
msg: err.message,
stack: err.stack
}
})
}
})
- 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:
- Sensitive Information Leakage: Check if the code contains sensitive information like API keys
- XSS Protection: Ensure all dynamic content is securely processed
- 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:
- Code Linting: Use ESLint to ensure consistent code style
- Automated Builds: Use CI tools to automatically package and upload alpha versions
- 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:
- Payment Process: Use sandbox environments to test the complete payment flow
- User Authorization: Simulate various authorization rejection scenarios
- 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
上一篇:小程序的安全机制
下一篇:小程序的版本管理与发布流程