test_store_v2.uts 2.77 KB
import { watch } from "vue";

import { state as rawState, store } from "@/store/index.uts";
import { AudioStateType } from "@/store/modules/audio.uts";
import { UserStateType } from "@/store/modules/user.uts";

export function runStoreTest() {
	console.log("=== 开始 Store 测试 (V2) ===");

	// 1. 基础对象获取
	// store 在 UTS 中作为导入对象,视为 UTSJSONObject
	const storeObj = store as UTSJSONObject;
	const getters = storeObj.getters as UTSJSONObject;
	
	// Access state directly (Strong Typed) to avoid ClassCastException
	// rawState is RootStateReactiveObject
	const state = rawState; 
	// Cast to UserState explicitly as rawState.user might be reactive proxy
	const userState = state.user as UserStateType;

	// 2. 初始状态检查
	// getters["key"] 返回 Any?,强制转换为函数类型
	const customerInfoGetter = getters.customerInfo as () => UTSJSONObject;
	const initCustomerInfo = customerInfoGetter();
	console.log(`初始 customerInfo: ${JSON.stringify(initCustomerInfo)}`);
    
	// 3. 设置监听器
	// userState.customerInfo is UTSJSONObject
	const stopWatch = watch(
		(): UTSJSONObject => userState.customerInfo,
		(newVal: UTSJSONObject, oldVal: UTSJSONObject) => {
			console.log(`[Watch] customerInfo 发生变化: ${JSON.stringify(newVal)}`);
		},
		{ deep: true }
	);

	// 4. 执行 Commit
	console.log("执行 commit('setCustomerInfo', { customerName: '测试用户' })...");
	const commitFn = storeObj.commit as (type: string, payload: any) => void;
	commitFn("setCustomerInfo", { customerName: "测试用户" });

	// 5. 验证状态
	const newCustomerInfo = userState.customerInfo;
	// newCustomerInfo is UTSJSONObject, use bracket access
	const pass1 = newCustomerInfo.customerName == "测试用户";
	console.log(`验证 State 更新: ${pass1 ? "PASS" : "FAIL"} (期望: '测试用户', 实际: '${newCustomerInfo.customerName}')`);

	// 6. 验证 Getter
	const getterVal = customerInfoGetter();
	const pass2 = getterVal.customerName == "测试用户";
	console.log(`验证 Getter 获取: ${pass2 ? "PASS" : "FAIL"} (期望: '测试用户', 实际: '${getterVal.customerName}')`);

	// 7. 测试 Dispatch
	console.log("执行 dispatch('setReceptionStatus', 'recording')...");
	const dispatchFn = storeObj.dispatch as (action: string, payload: any) => any | null;
	dispatchFn("setReceptionStatus", "recording");
    
	// Cast to AudioState explicitly
	const audioState = state.audio as AudioStateType;
	const status = audioState.receptionStatus;
	const pass3 = status == "recording";
	console.log(`验证 Audio State 更新: ${pass3 ? "PASS" : "FAIL"} (期望: 'recording', 实际: '${status}')`);

	// 8. 清理
	stopWatch();
    
	// 恢复状态
	commitFn("clearCustomerInfo", {});
	dispatchFn("setReceptionStatus", "");

	console.log("=== Store 测试结束 ===");
}