chrome插件开发-自动化脚本(2)

1,647 阅读1分钟

页面自动化测试

接上一篇文章 chrome插件开发-自动化脚本(1)

之前只是可以运行脚本. 但是运行的结果也是我想知道的,所以优化了一些内容.

因为我自己的项目是前后端分离的, 所以目前只做了简单的ajax请求和新开浏览器tab的测试结果.

测试接口请求

使用chrome.devtools.network.onRequestFinished.addListener(this.onRequestFinished)接口监听每个请求,和配置的url和method匹配然后记录下状态码就算完成了.

onRequestFinished (request) {
  // 1. 判断当前执行的用例是否配置了response
  // 2. 匹配结果,输出表格
  let requestUrl = getUrlPath(request.request.url)
  if ((request._resourceType === 'xhr' || request._resourceType === 'fetch') &&
    this.runningIndex !== -1 &&
    this.caseList[this.runningIndex].responseConfig
  ) {
    // console.log('onRequestFinished', requestUrl)
    let configList = this.caseList[this.runningIndex].responseConfig.filter(item => item.type === 'ajax')
    configList.forEach(config => {
      if (requestUrl.endsWith(config.url) && request.request.method === config.method.toUpperCase()){
        this.result[this.caseList[this.runningIndex].name].push({
          type: config.type,
          url: request.request.url,
          method: request.request.method,
          status: request.response.status
        })
      }
    })
  }
},

测试新开浏览器tab

首先需要在background.js中监听tab的激活情况

// 监听测试用例的测试结果是打开新页面的情况
chrome.tabs.onActivated.addListener(function (activeInfo) {
  if (runningTabId && connections[runningTabId]) {
    chrome.tabs.get(activeInfo.tabId, function (tab) {
      connections[runningTabId].postMessage({
        type: 'tab-activated',
        tab: tab
      })
    })
  }
})

然后在Main.vue中通过eventbus方式发送给各个订阅这个消息的组件.

this.backgroundPageConnection.onMessage.addListener((message) => {
  this.$store.commit('setDisConnect', false)
  switch (message.type) {
    case 'tab-activated':
      // 发送eventbus home.vue 执行时监听
      this.$EventBus.$emit('tab-activated', message.tab)
      break
  }
})

home.vue页面组件中订阅, 判断方式和接口测试的基本一致

this.$EventBus.$on('tab-activated', this.onTabActivated)

onTabActivated (activatedTab) {
  // console.log('onEventBus tab-activated', activatedTab)
  if (this.runningIndex !== -1 && this.caseList[this.runningIndex].responseConfig) {
    let configList = this.caseList[this.runningIndex].responseConfig.filter(item => item.type === 'newTab')
    configList.forEach(config => {
      if (activatedTab.pendingUrl.endsWith(config.url)) {
        this.result[this.caseList[this.runningIndex].name].push({
          type: config.type,
          url: activatedTab.pendingUrl
        })
      }
    })
  }
},

监听时机

这些事件只需要在自动脚本运行时监听,其他时候是不用监听的.

// 运行时监听新开页面
this.$EventBus.$on('tab-activated', this.onTabActivated)
// 运行时监听网络请求
chrome.devtools.network.onRequestFinished.addListener(this.onRequestFinished)

// 解除监听
this.$EventBus.$off('tab-activated')
chrome.devtools.network.onRequestFinished.removeListener(this.onRequestFinished)

演示效果

先看演示效果吧 chrome插件-自动化脚本 批量测试演示