Detailed explanation of small program automated testing
Aug 21, 2020 pm 05:11 PM[Related learning recommendations: WeChat Mini Program Tutorial]
Background
The team plans to do a mini program automated test in the near future The tool is expected to enable business personnel to automatically restore the previous operation path after operating the mini program, and capture exceptions that occur during the operation to determine whether this release will affect the basic functions of the mini program.

The above description seems simple, but there are still some difficulties in the middle. The first difficulty is how to record the operations when business personnel operate the mini program. path, the second difficulty is how to restore the recorded operation path.
Automation SDK
How to restore the operation path to this problem, the official SDK is preferred: miniprogram-automator
.
The Mini Program Automation SDK provides developers with a set of solutions to control mini programs through external scripts, thereby achieving the purpose of automated testing of mini programs. Through this SDK, you can do the following:
- Control the mini program to jump to the specified page
- Get the mini program page data
- Get the mini program page elements Status
- Trigger mini program element binding event
- Inject code snippet into AppService
- Call any interface on wx object
- ...
The above descriptions are all from official documents. It is recommended to read the official documents before reading the following content. Of course, if you have used puppeteer before, you can also get started quickly. The API is basically the same. The following is a brief introduction to how to use the SDK.
//?引入sdkconst?automator?=?require('miniprogram-automator')//?啟動微信開發(fā)者工具automator.launch({??//?微信開發(fā)者工具安裝路徑下的?cli?工具 ??//?Windows下為安裝路徑下的?cli.bat ??//?MacOS下為安裝路徑下的?cli ??cliPath:?'path/to/cli',??//?項目地址,即要運(yùn)行的小程序的路徑 ??projectPath:?'path/to/project', }).then(async?miniProgram?=>?{?//?miniProgram?為?IDE?啟動后的實例 ????//?啟動小程序里的?index?頁面 ??const?page?=?await?miniProgram.reLaunch('/page/index/index')??//?等待?500?ms ??await?page.waitFor(500)??//?獲取頁面元素 ??const?element?=?await?page.$('.main-btn')??//?點擊元素 ??await?element.tap()????//?關(guān)閉?IDE ??await?miniProgram.close() })復(fù)制代碼
There is one thing that needs to be reminded: before using the SDK, you need to open the service port of the developer tools, otherwise the startup will fail.

Capture user behavior
With the method of restoring the operation path, the next step is to solve the problem of recording the operation path.
In the mini program, it is not possible to capture all events in the window through event bubbling like in the web. Fortunately, all pages and components of the mini program must pass Page
, Component
method to wrap, so we can rewrite these two methods, intercept the incoming method, and determine whether the first parameter is an event
object to capture all events .
//?暫存原生方法const?originPage?=?Pageconst?originComponent?=?Component//?改寫?PagePage?=?(params)?=>?{??const?names?=?Object.keys(params)??for?(const?name?of?names)?{????//?進(jìn)行方法攔截 ????if?(typeof?obj[name]?===?'function')?{ ??????params[name]?=?hookMethod(name,?params[name],?false) ????} ??} ??originPage(params) }//?改寫?ComponentComponent?=?(params)?=>?{??if?(params.methods)?{??????const?{?methods?}?=?params??????const?names?=?Object.keys(methods)??????for?(const?name?of?names)?{????????//?進(jìn)行方法攔截 ????????if?(typeof?methods[name]?===?'function')?{ ??????????methods[name]?=?hookMethod(name,?methods[name],?true) ????????} ??????} ??} ??originComponent(params) }const?hookMethod?=?(name,?method,?isComponent)?=>?{??return?function(...args)?{????const?[evt]?=?args?//?取出第一個參數(shù) ????//?判斷是否為?event?對象 ????if?(evt?&&?evt.target?&&?evt.type)?{??????//?記錄用戶行為 ????}????return?method.apply(this,?args) ??} }復(fù)制代碼
The code here only proxies all event methods and cannot be used to restore the user's behavior. To restore the user's behavior, you must also know whether the event type is required, such as click, long press, and input.
const?evtTypes?=?[????'tap',?//?點擊 ????'input',?//?輸入 ????'confirm',?//?回車 ????'longpress'?//?長按]const?hookMethod?=?(name,?method)?=>?{??return?function(...args)?{????const?[evt]?=?args?//?取出第一個參數(shù) ????//?判斷是否為?event?對象 ????if?( ??????evt?&&?evt.target?&&?evt.type?&& ??????evtTypes.includes(evt.type)?//?判斷事件類型 ????)?{??????//?記錄用戶行為 ????}????return?method.apply(this,?args) ??} }復(fù)制代碼
After determining the event type, you still need to clarify which element was clicked. However, the pitfall in the mini program is that there is no class name of the element in the target attribute of the event object, but the element can be obtained. dataset.

In order to obtain the elements accurately, we need to add a step in the construction, modify the wxml file, and change the class## of all elements # Copy the attribute to
data-className.
<!-- 構(gòu)建前 --><view></view><view></view><!-- 構(gòu)建后 --><view></view><view></view>復(fù)制代碼But after obtaining the class, there will be another pitfall. The automated testing tool of the mini program cannot directly obtain the elements in the custom component in the page. The custom component must be obtained first.
<!-- Page --><toast></toast><!-- Component --><view> ??<text>{{text}}</text> ??<view></view></view>復(fù)制代碼
//?如果直接查找?.toast-close?會得到?nullconst?element?=?await?page.$('.toast-close') element.tap()?//?Error!//?必須先通過自定義組件的?tagName?找到自定義組件//?再從自定義組件中通過?className?查找對應(yīng)元素const?element?=?await?page.$('toast?.toast-close') element.tap()復(fù)制代碼So when we build the operation, we also need to insert tagName for the element.
<!-- 構(gòu)建前 --><view></view><toast></toast><!-- 構(gòu)建后 --><view></view><toast></toast>復(fù)制代碼Now we can continue happily recording user behavior.
//?記錄用戶行為的數(shù)組const?actions?=?[];//?添加用戶行為const?addAction?=?(type,?query,?value?=?'')?=>?{ ??actions.push({????time:?Date.now(), ????type, ????query, ????value ??}) }//?代理事件方法const?hookMethod?=?(name,?method,?isComponent)?=>?{??return?function(...args)?{????const?[evt]?=?args?//?取出第一個參數(shù) ????//?判斷是否為?event?對象 ????if?( ??????evt?&&?evt.target?&&?evt.type?&& ??????evtTypes.includes(evt.type)?//?判斷事件類型 ????)?{??????const?{?type,?target,?detail?}?=?evt??????const?{?id,?dataset?=?{}?}?=?target????????const?{?className?=?''?}?=?dataset????????const?{?value?=?''?}?=?detail?//?input事件觸發(fā)時,輸入框的值 ??????//?記錄用戶行為 ??????let?query?=?'' ??????if?(isComponent)?{????????//?如果是組件內(nèi)的方法,需要獲取當(dāng)前組件的?tagName ????????query?=?`${this.dataset.tagName}?` ??????}??????if?(id)?{????????//?id?存在,則直接通過?id?查找元素 ????????query?+=?id ??????}?else?{????????//?id?不存在,才通過?className?查找元素 ????????query?+=?className ??????} ??????addAction(type,?query,?value) ????}????return?method.apply(this,?args) ??} }復(fù)制代碼Up to this point, all the user’s clicks, inputs, and enter-related operations have been recorded. However, the scrolling screen operation is not recorded. We can directly proxy the
onPageScroll method of Page.
//?記錄用戶行為的數(shù)組const?actions?=?[];//?添加用戶行為const?addAction?=?(type,?query,?value?=?'')?=>?{??if?(type?===?'scroll'?||?type?===?'input')?{????//?如果上一次行為也是滾動或輸入,則重置?value?即可 ????const?last?=?this.actions[this.actions.length?-?1]????if?(last?&&?last.type?===?type)?{ ??????last.value?=?value ??????last.time?=?Date.now()??????return ????} ??} ??actions.push({????time:?Date.now(), ????type, ????query, ????value ??}) } Page?=?(params)?=>?{??const?names?=?Object.keys(params)??for?(const?name?of?names)?{????//?進(jìn)行方法攔截 ????if?(typeof?obj[name]?===?'function')?{ ??????params[name]?=?hookMethod(name,?params[name],?false) ????} ??}??const?{?onPageScroll?}?=?params??//?攔截滾動事件 ??params.onPageScroll?=?function?(...args)?{????const?[evt]?=?args????const?{?scrollTop?}?=?evt ????addAction('scroll',?'',?scrollTop) ????onPageScroll.apply(this,?args) ??} ??originPage(params) }復(fù)制代碼There is an optimization point here, that is, when the scroll operation is recorded, you can judge whether the last operation was also a scroll operation. If it is the same operation, you only need to modify the scroll distance, because the two The second scroll can be done in one step. In the same way, the same is true for input events, and the input value can also be reached in one step. Restore user behaviorAfter the user operation is completed, the json text of the user behavior can be output on the console. After copying the json text, it can be run through the automation tool.
//?引入sdkconst?automator?=?require('miniprogram-automator')//?用戶操作行為const?actions?=?[ ??{?type:?'tap',?query:?'goods?.title',?value:?'',?time:?1596965650000?}, ??{?type:?'scroll',?query:?'',?value:?560,?time:?1596965710680?}, ??{?type:?'tap',?query:?'gotoTop',?value:?'',?time:?1596965770000?} ]//?啟動微信開發(fā)者工具automator.launch({??projectPath:?'path/to/project', }).then(async?miniProgram?=>?{??let?page?=?await?miniProgram.reLaunch('/page/index/index')?? ??let?prevTime??for?(const?action?of?actions)?{????const?{?type,?query,?value,?time?}?=?action????if?(prevTime)?{??????//?計算兩次操作之間的等待時間 ????????await?page.waitFor(time?-?prevTime) ????}????//?重置上次操作時間 ????prevTime?=?time???? ????//?獲取當(dāng)前頁面實例 ????page?=?await?miniProgram.currentPage()????switch?(type)?{??????case?'tap':????????????const?element?=?await?page.$(query)????????await?element.tap()????????break;??????case?'input':????????????const?element?=?await?page.$(query)????????await?element.input(value)????????break;??????case?'confirm':????????????const?element?=?await?page.$(query)????????????????await?element.trigger('confirm',?{?value?});????????break;??????case?'scroll':????????await?miniProgram.pageScrollTo(value)????????break; ????}????//?每次操作結(jié)束后,等待?5s,防止頁面跳轉(zhuǎn)過程中,后面的操作找不到頁面 ????await?page.waitFor(5000) ??}????//?關(guān)閉?IDE ??await?miniProgram.close() })復(fù)制代碼This is just a simple restoration of the user's operation behavior. During the actual operation, network requests and localstorage mocks will also be involved, which will not be described here. At the same time, we can also access the jest tool to make it easier to write use cases.
Summary
For seemingly difficult needs, as long as you explore them carefully, you can always find a corresponding solution. In addition, there are really many pitfalls in the automation tools of WeChat mini programs. If you encounter problems, you can first go to the mini program community to find them. Most of the pitfalls have been stepped on by predecessors. There are also some problems that cannot be solved at the moment and you can only find other ways to solve them. avoid. Finally, I wish the world is bug-free.
Related learning recommendations: WeChat public account development tutorial
The above is the detailed content of Detailed explanation of small program automated testing. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How to Delete Apple Shortcut Automation With the launch of Apple's new iOS13 system, users can use shortcuts (Apple Shortcuts) to customize and automate various mobile phone operations, which greatly improves the user's mobile phone experience. However, sometimes we may need to delete some shortcuts that are no longer needed. So, how to delete Apple shortcut command automation? Method 1: Delete through the Shortcuts app. On your iPhone or iPad, open the "Shortcuts" app. Select in the bottom navigation bar

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Compare SpringBoot and SpringMVC and understand their differences. With the continuous development of Java development, the Spring framework has become the first choice for many developers and enterprises. In the Spring ecosystem, SpringBoot and SpringMVC are two very important components. Although they are both based on the Spring framework, there are some differences in functions and usage. This article will focus on comparing SpringBoot and Spring

Automation technology is being widely used in different industries, especially in the supply chain field. Today, it has become an important part of supply chain management software. In the future, with the further development of automation technology, the entire supply chain and supply chain management software will undergo major changes. This will lead to more efficient logistics and inventory management, improve the speed and quality of production and delivery, and in turn promote the development and competitiveness of enterprises. Forward-thinking supply chain players are ready to deal with the new situation. CIOs should take the lead in ensuring the best outcomes for their organizations, and understanding the role of robotics, artificial intelligence, and automation in the supply chain is critical. What is supply chain automation? Supply chain automation refers to the use of technological means to reduce or eliminate human participation in supply chain activities. it covers a variety of

Using Python scripts to implement task scheduling and automation under the Linux platform In the modern information technology environment, task scheduling and automation have become essential tools for most enterprises. As a simple, easy-to-learn and feature-rich programming language, Python is very convenient and efficient to implement task scheduling and automation on the Linux platform. Python provides a variety of libraries for task scheduling, the most commonly used and powerful of which is crontab. crontab is a management and scheduling system

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.
