All files / mp ensureInMiniProgram.ts

80% Statements 4/5
75% Branches 3/4
100% Functions 1/1
80% Lines 4/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22                          17x 7x   17x 17x        
import { inMiniProgram } from '../utils'
 
let $mp: ReturnType<typeof inMiniProgram> | undefined
 
/**
 * 确保当前在小程序环境并执行回调。
 *
 * @param cb 要执行的回调,第一个参数为小程序 API 挂载的全局变量
 * @returns 返回回调的执行结果
 */
export function ensureInMiniProgram<T>(
  cb: (mp: Exclude<typeof $mp, false | undefined>) => T,
): T {
  if ($mp === undefined) {
    $mp = inMiniProgram()
  }
  if ($mp) {
    return cb($mp)
  }
  throw new Error('不在小程序环境中')
}