Home > WeChat Applet > Mini Program Development > wx API interception for small program automated testing

wx API interception for small program automated testing

coldplay.xixi
Release: 2020-11-13 17:32:09
forward
3200 people have browsed it

WeChat Mini Program Development TutorialWx API interception for automated testing of column mini programs.

wx API interception for small program automated testing

As small programs become more and more widely used, our front-end development work has also changed from pure web development to Expand to cross-end development of web applets. In order to improve research and development efficiency, more and more web modules need to be migrated, updated, and compatible with small programs to achieve cross-terminal reuse. These modules will also undergo iterations and version updates following the business. At this time, we need to have good testing to ensure the reliability of each end module.

Since we migrated many existing web modules to mini programs, the testing on the web side is relatively complete. Therefore, what we need to consider is:

  1. How to quickly migrate existing web use cases to small programs

  2. For new modules, how to quickly write use cases at both ends.

(We mainly use the combination of Puppeteer and Jest on the web side.)

You can move directly to the final solution

Test module type

Our current modules are mainly of the following three types:

  1. Environment-independent logic layer module
  2. Environment-related logic layer module
  3. UI component module associated with the environment

Type 1 modules are not restricted by the environment and can share unit tests with the web without the need for additional test case development.

Type 3 modules are difficult to reuse due to the large differences between the mini program and the web (currently our web UI layer is mainly based on React, the mini program is developed natively, and kbone is used to develop some pages. Isomorphic development).

Here we mainly migrate test cases for modules of type 2.

Selection of mini program testing tools

The mini program official currently provides two tools to support mini program testing:

  1. Component unit testing provides a testing tool Set to support custom components running in nodejs single thread.
  2. Mini Program Automation provides developers with a set of solutions to control mini programs through external scripts.

Through official tools combined with testing frameworks such as Jest and Mocha, we can implement testing in a small program environment.

We chose Mini Program Automation. Similar to running web-side tests in Puppeteer, we can automate the mini program and control the developer tools to implement testing in the mini program environment. The similarities between the two provide us with the possibility of cross-end migration and even reuse of test cases.

How to migrate test cases

Take migrating a test case of a reporting module as an example. The following is a test case of a web reporting module that we already have.

Web test case

The path covered by this use case is: Call the imlog.default.error() method-> The browser will initiate a request-> Correct the request parameters Check .

test('.error()调用正常', async done => {  const opts = {    project: 'imlogtest',
  };  // 检查上报请求的参数
  const expector = req => {    try {      const url = req.url();      const method = req.method();      const headers = req.headers();      const body = req.postData();      const data = JSON.parse(body);

      expect(url).toBe(DEFAULT_URL); // 请求的url符合预期
      expect(method).toBe('POST'); // 请求的method符合预期
      expect(headers['content-type']).toBe('text/plain'); // 请求的contentType符合预期
      expect(data.url).toBe(TEST_PAGE_URL); // 请求体的url字段符合预期

      done();
    } catch(error) {
      done(error);
    }
  };  // 监听上报请求并校验参数
  page.once('request', expector);  // 在浏览器中执行上报
  page.evaluate(    (o) => {      const reportor = window.imlog.default;
      reportor.config(o);
      reportor.error('test'); // 进行上报
    },
    opts
  );
});复制代码
Copy after login

The above mainly uses Puppeteer's Page API.

  • page.evaluate controls the page to execute a piece of logic (executes imlog.default.error())
  • page.once('request', expector) listens to page requests and obtains parameters (Detect whether a request is initiated and verify the request parameters)

Imagination of mini program use cases

Mini program automation provides us with some APIs similar to puppeteer:

  • miniProgram.evaluate controls the mini program to inject code snippets into AppService and returns the execution results

If the mini program can be like Puppeteer, it can intercept the calling parameters of wx API in the form of listening events, test cases Writing will be much easier. The mini program use case we imagine will be in the following form:

test('.error()调用正常', async done => {  const opts = {    project: 'imlogtest',
  };  // 检查上报请求的参数
  const expector = req => {    try {      // diff:按照特定格式解析出小程序请求参数
      const {url, method, headers, body, data} = parseWxReqParams(req); 

      expect(url).toBe(DEFAULT_URL); // 请求的url符合预期
      expect(method).toBe('POST'); // 请求的method符合预期
      expect(headers['content-type']).toBe('text/plain'); // 请求的contentType符合预期
      expect(data.url).toBe(TEST_PAGE_URL); // 请求体的url字段符合预期

      done();
    } catch(error) {
      done(error);
    }
  };  // 监听上报请求并校验参数
  // todo: miniProgram对象支持once/on等事件方法
  miniProgram.once('request', expector);  // 在小程序中执行上报
  miniProgram.evaluate(    (o) => {      // diff: 请求方法挂在小程序app对象上
      const reportor = getApp().imlog.default;
      reportor.config(o);
      reportor.error('test'); // 进行上报
    },
    opts
  );
});复制代码
Copy after login

As long as we find a way to monitor the call through miniProgram.on('api', fn) in the form of events Parameters passed during API.

In this form, the only difference between the web and mini program use cases is:

  1. The operation of the page object in the web is transferred to the mini program miniProgram object to complete
  2. The method of mounting under the window in the web, and the method of mounting under the app in the applet
  3. The way web and applet parse request parameters are different

wx API interception method

First observe the miniProgram object. Through the MiniProgram.d.ts exposed by miniprogram-automator, you can find that the MiniProgram class itself inherits from EventEmitter.

import { EventEmitter } from 'events';export default class MiniProgram extends EventEmitter {  // ...}复制代码
Copy after login

Next, you need to find a way to trigger the emit method of the miniProgram object when the api is called.

There are two automation APIs that can help us achieve this.

  • miniProgram.mockWxMethod allows us to override the results of calling a specified method on a wx object.

  • miniProgram.exposeFunction exposes methods globally in AppService for the mini program to call methods in test scripts.

At this moment, a bold idea came to my mind

The above is the detailed content of wx API interception for small program automated testing. For more information, please follow other related articles on the PHP Chinese website!

source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template