| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- 'use strict';
- const test = require('node:test');
- const assert = require('node:assert/strict');
- const fs = require('node:fs');
- const path = require('node:path');
- const root = path.resolve(__dirname, '..');
- const util = require('../utils/util.js');
- test('登录和会话校验保留微信 SDK 合约', async t => {
- t.after(() => { delete global.wx; });
- global.wx = { login: opt => opt.success({ code: 'synthetic-code' }), checkSession: opt => opt.success() };
- assert.deepEqual(await util.login(), { code: 'synthetic-code' });
- assert.equal(await util.checkSession(), true);
- global.wx.checkSession = opt => opt.fail();
- await assert.rejects(util.checkSession(), reason => reason === false);
- });
- test('页面入口和分享可解析,移除的传输函数不再导出', t => {
- t.after(() => { delete global.Page; delete global.wx; });
- const manifest = require('../app.json');
- const pages = [...manifest.pages, ...manifest.subpackages.flatMap(pkg => pkg.pages.map(p => pkg.root + '/' + p))];
- for (const page of pages) {
- for (const ext of ['.js', '.wxml']) assert.ok(fs.existsSync(path.join(root, page + ext)));
- }
- let page, title;
- global.Page = definition => { page = definition; };
- global.wx = { setNavigationBarTitle: value => { title = value.title; } };
- require('../yuban/pages/index/index.js');
- page.onLoad({});
- assert.equal(title, '语伴');
- assert.ok(pages.includes(page.onShareAppMessage().path));
- assert.equal(Object.hasOwn(util, 'sentRes'), false);
- });
- test('通用业务页经已登记登录页恢复原目标,保留查询与片段', async () => {
- const vm = require('node:vm');
- const target = require('../utils/web-view-target');
- const manifest = require('../app.json');
- const routes = new Set([...manifest.pages,...manifest.subpackages.flatMap(pkg=>pkg.pages.map(page=>pkg.root+'/'+page))]);
- const history = [];
- const storage = new Map();
- let user, currentPage;
- const app = {Parse:{User:{current:()=>user}},globalData:{company:'synthetic'},checkAuth:async()=>Boolean(user)};
- const wx = {
- getStorageSync:key=>storage.get(key),setStorageSync:(key,value)=>storage.set(key,value),
- redirectTo:({url})=>{const address=new URL(url,'https://local.invalid');assert.ok(routes.has(address.pathname.slice(1)));history.push(address);},
- showToast(){},getLaunchOptionsSync:()=>({scene:1001}),
- };
- const load = file => {
- const context = vm.createContext({
- wx,getApp:()=>app,getCurrentPages:()=>[currentPage],console:{log(){},debug(){},error(){},warn(){}},
- require:name=>{
- if (name.endsWith('web-view-target')) return target;
- if (name==='./share') {
- const module={exports:{}};
- const code=fs.readFileSync(path.join(root,'common-page/pages/web-view/share.js'),'utf8');
- vm.runInContext('(function(module,exports){'+code+'})',context)(module,module.exports);
- return module.exports;
- }
- return {};
- },
- Page:def=>{currentPage={...def,data:{...def.data},setData(value){Object.assign(this.data,value);}};},
- });
- vm.runInContext(fs.readFileSync(path.join(root,file),'utf8'),context);
- return currentPage;
- };
- const original='https://www.yuban.co/user-profile/memory-cleanup?tab=people&label=a%26b#family';
- const web=load('common-page/pages/web-view/index.js');
- const opts={path:encodeURIComponent(original),source:'mini'};
- await web.onLoad(opts);
- const authRoute=history.pop();
- assert.equal(authRoute.pathname,'/components/app-auth/index');
- assert.equal(web.data.path,'');
- const expected=original.replace('#family','&source=mini#family');
- assert.equal(authRoute.searchParams.get('returnUrl'),expected);
- const auth=load('components/app-auth/index.js');auth.options=Object.fromEntries(authRoute.searchParams);
- user={id:'fixture-member',get:key=>({mobile:'fixture-mobile',nickname:'测试会员'})[key],getSessionToken:()=>'fixture-session'};
- await auth.getUserProfile();
- const returned=history.pop();assert.equal(returned.pathname,'/common-page/pages/web-view/index');
- assert.equal(returned.searchParams.get('path'),expected);
- const resumed=load('common-page/pages/web-view/index.js');
- await resumed.onLoad(Object.fromEntries(returned.searchParams));
- const final=new URL(resumed.data.path);
- assert.equal(final.pathname,'/user-profile/memory-cleanup');assert.equal(final.hash,'#family');
- assert.equal(final.searchParams.get('label'),'a&b');assert.equal(final.searchParams.get('source'),'mini');
- assert.equal(final.searchParams.has('token'),false);assert.equal(final.searchParams.has('userId'),false);assert.equal(final.searchParams.has('mobile'),false);
- });
- test('引导页会话信息与已有受控业务路径兼容', () => {
- const {readTarget,requestedTarget,withQuery}=require('../utils/web-view-target');
- const path='https://www.yuban.co/home?fromStartup=1&source=wechat-miniprogram#start';
- const url=new URL(requestedTarget({path:encodeURIComponent(path),skipAuth:'true',sessionToken:'fixture-session',mobile:'fixture-mobile'}));
- assert.equal(url.searchParams.has('sessionToken'),false);assert.equal(url.searchParams.has('mobile'),false);
- assert.equal(url.hash,'#start');assert.equal(url.searchParams.getAll('source').length,1);assert.equal(url.searchParams.has('skipAuth'),false);
- assert.equal(readTarget('%broken'),'');
- for(const name of ['products','cases','home']) {
- const legacy='https://app.fmode.cn/dev/pobingfeng/owner/nav/'+name+'?storeId=sample';
- assert.equal(readTarget(encodeURIComponent(legacy)),legacy);
- assert.equal(requestedTarget({path:legacy+'&token=sample-token&mobile=sample-mobile',source:'mini'}),legacy+'&source=mini');
- }
- });
- test('语伴引导与三条旧商城导航只传业务参数,保留 H5 支付回调', async () => {
- const vm=require('node:vm');
- const {requestedTarget}=require('../utils/web-view-target');
- let home,index,navigation;
- const wx={getStorageSync(){throw Error('Home must not read native identity');},redirectTo:options=>{navigation=options.url;}};
- vm.runInNewContext(fs.readFileSync(path.join(root,'yuban/components/home/index.js'),'utf8'),{Component:def=>{home=def.methods;},wx,require:()=>require('../utils/web-view-target')});
- function target(route) {
- const target=new URL(new URL(route,'https://local.invalid').searchParams.get('path'));
- for(const key of ['userId','mobile','token','sessionToken'])assert.equal(target.searchParams.has(key),false);
- return target;
- }
- const launch=target(home.buildWebViewPath.call(home));
- assert.equal(launch.pathname,'/home');assert.deepEqual([...launch.searchParams.keys()],['fromStartup','source']);
- wx.getStorageSync=()=>null;
- vm.runInNewContext(fs.readFileSync(path.join(root,'index.js'),'utf8'),{
- Page:def=>{index=def;},wx,require:()=>({default:{}}),requirePlugin:()=>({}),
- console:{log(){},error(){}},
- });
- for(const [method,itemKey,route] of [['redirectToProductDetail','productId','products'],['redirectToCaseDetail','caseId','cases'],['redirectToStoreWithPlan','planId','home']]){
- navigation=null;await index[method]('s&1','item?42','synthetic');
- const dest=target(navigation);assert.equal(dest.pathname,'/dev/pobingfeng/owner/nav/'+route);
- assert.equal(dest.searchParams.get(itemKey),'item?42');assert.equal(dest.searchParams.get('storeId'),'s&1');assert.equal(dest.searchParams.get('guestMode'),'true');
- }
- const pay='https://www.yuban.co/user-profile/membership-renewal?code=payment-code&state=payment-state&invite=keep';
- assert.equal(requestedTarget({path:pay+'&token=fixture'}),pay);
- assert.equal(requestedTarget({path:'https://www.yuban.co/home?sessionToken=fixture&invite=keep&code=old#part'}),'https://www.yuban.co/home?invite=keep#part');
- });
|