第一卷 / 第 06 章
面向应用开发者
测试用户流程
编写 Jasmine 测试,并在 C++ 应用的页面中运行。
排版约定
函数名、类型、命令、选项和文件名使用等宽字体,例如 describe、wf test 或 main.cpp。术语首次定义时用强调标出。代码块给出需要输入的内容;前面的正文说明其位置和前提条件。
Jasmine 测试的组成
Jasmine 是一个 JavaScript 测试库。一个测试描述一项操作,并检查它应当产生的结果。本章使用以下函数:
describe把涉及同一行为的测试归为一组。it定义一个测试用例。expect检查结果的某个值或属性。beforeAll准备一组测试共用的条件。beforeEach在每个用例之前建立所需的条件。
异步测试可以用 async 和 await 等待 C++ 的回复。我们先测试数据格式,再在真实界面中测试一个流程。
检查网格格式
在 WebFront 终端中,用 wf install jasmine-core@7.0.2 安装 Jasmine。然后在 life-project 中创建 tests/life.spec.js。
下面的测试检查三个细胞在字节数组中的打包方式。它针对的是 JavaScript 中的网格表示,还没有检查由 C++ 计算的 Conway 规则。
describe('the Life grid', () => {
it('packs 1024 cells into 128 bytes', () => {
const cells = new Uint8Array(32 * 32 / 8);
for (const i of [330, 331, 332])
cells[i >> 3] |= 1 << (i & 7);
expect(cells.length).toBe(128);
expect(cells[41]).toBe(0b00011100);
});
});声明测试文件
在 webfront.project.json 的根对象中加入以下属性,并保留 JSON 所需的逗号。wf init 不会创建这一配置。
运行 wf test。Jasmine 会在窗口中加载,断言不成立时命令失败。要验证这一行为,可以暂时把测试中的 128 改为 127,然后再改回正确的值。
"test": {"specs": ["tests/life.spec.js"]}检查 TypeScript 类型
在 life-project 根目录中创建 tsconfig.json,内容如下。类型检查会使用锁文件中记录的 TypeScript 版本。
类型检查和测试执行的目的不同:前者检查程序的静态一致性,后者观察其运行时行为。
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"noEmit": true
},
"include": ["ui"]
}安装类型声明
模板导入了 React 和 React DOM。严格的检查需要它们的类型声明以及 TypeScript 编译器。下面的命令安装这些包并运行 wf check。
wf install typescript@5.9.3 @types/react@19.3.0 @types/react-dom@19.3.0
wf check测试项目或测试应用
wf test 使用开发项目清单中声明的测试规格,以及锁定版本的 jasmine-core。
要测试现有 C++ 应用的页面,也可以使用 webfront_add_jasmine_test。这个辅助函数把 Jasmine 和测试加载到应用的真实页面中,页面原有的脚本、DOM 元素和 C++ 回调都照常可用。
第二种方式与 CTest 集成。它不需要开发终端、wf 项目清单或宿主机上的 JavaScript 运行时,也不依赖 MCP。
示例界面
设想一个简单的报价界面。用户输入数量并请求计算。程序调用 C++ 函数 quote.calculate,并显示返回的总价。
创建 ui/index.html,内容如下。调用期间按钮保持禁用,错误显示在页面中。appReady 这个 Promise 属于本示例,并不是 WebFront 的属性。测试用它等待页面安装好事件处理函数。
<!doctype html>
<html lang="en"><meta charset="utf-8"><title>Quotation</title>
<label for="quantity">Quantity</label>
<input id="quantity" type="number" value="1" min="1">
<button id="calculate" disabled>Calculate</button>
<output id="total" aria-live="polite"></output>
<p id="status" role="status"></p>
<script src="/WebFront.js"></script>
<script>
const quantity = document.getElementById('quantity');
const button = document.getElementById('calculate');
const total = document.getElementById('total');
const status = document.getElementById('status');
window.appReady = webFront.ready.then(() => {
button.disabled = false;
button.addEventListener('click', async () => {
button.disabled = true;
status.textContent = 'Calculating';
total.textContent = '';
try {
const count = Number(quantity.value);
if (!Number.isInteger(count) || count < 1 || count > 1000)
throw new Error('Quantity must be between 1 and 1000');
total.textContent = String(await webFront.cppFunction('quote.calculate')(count));
status.textContent = 'Ready';
} catch (error) {
status.textContent = 'Error: ' + error.message;
} finally { button.disabled = false; }
});
});
window.appReady.catch(error => { status.textContent = 'Error: ' + error.message; });
</script></html>编写流程测试
创建 tests/ui/quote.spec.js。第一个用例输入 3 件,点击按钮,并检查显示的总价是否为 75。第二个用例输入无效的数量,并检查是否显示错误。
C++ 计算没有被模拟。因此第一个用例覆盖了点击处理、桥接、C++ 回调和界面更新。按钮重新可用时等待结束,上限为两秒。
这个测试产生的事件是合成事件。它不检查像素级布局、原生输入设备,也不检查全部无障碍属性。由 React 控制的输入框还需要合适的输入方式。
// tests/ui/quote.spec.js — classic JavaScript, loaded into the real page.
describe('quotation journey', () => {
beforeAll(async () => { await window.appReady; });
const element = id => document.getElementById(id);
function until(predicate) {
if (predicate()) return Promise.resolve();
return new Promise((resolve, reject) => {
const observer = new MutationObserver(() => {
if (predicate()) { cleanup(); resolve(); }
});
const timer = setTimeout(() => {
cleanup(); reject(new Error('UI did not settle within 2 seconds'));
}, 2000);
function cleanup() { clearTimeout(timer); observer.disconnect(); }
observer.observe(document.body, {
subtree: true, childList: true, characterData: true, attributes: true
});
});
}
it('enters a quantity and displays the C++ price', async () => {
element('quantity').value = '3';
element('quantity').dispatchEvent(new Event('input', {bubbles: true}));
element('calculate').click();
await until(() => !element('calculate').disabled);
expect(element('status').textContent).toBe('Ready');
expect(element('total').textContent).toBe('75');
});
it('shows an error for an invalid quantity', async () => {
element('quantity').value = '0';
element('calculate').click();
await until(() => !element('calculate').disabled);
expect(element('status').textContent).toContain('Error:');
expect(element('total').textContent).toBe('');
});
it('documents the calculated quotation', async () => {
await window.appReady;
document.getElementById('quantity').value = '3';
document.getElementById('calculate').click();
await until(() => !document.getElementById('calculate').disabled);
expect(document.getElementById('total').textContent).toBe('75');
await webFrontCapture.screenshot('quote-75');
});
});准备 C++ 应用
下面的 main.cpp 使用 EmbeddedWebFront,由 CMake 启用 WKWebView,需要 macOS 13.3 或更高版本。端口 0 让操作系统选择一个空闲端口。文档根目录 ui 相对于 CMake 中设置的工作目录。
必须在调用 show 之前创建 JasmineTest 对象。窗口关闭后,shutdown 等待操作结束,exitCode() 给出应返回的状态。
CMake 辅助函数会为该目标定义 WEBFRONT_JASMINE_TESTING。没有这个宏时,JasmineTest 不起作用。请把用于分发的目标与插桩测试目标分开。
#include <webfront/WebFront.hpp>
#include <webfront/testing/Jasmine.hpp>
#include <stdexcept>
#include <iostream>
#include <string_view>
using App = webfront::EmbeddedWebFront;
int main(int argc, char** argv) {
if (argc == 2 && std::string_view{argv[1]} == "--version") {
std::cout << "Quote 1.0\n";
return 0;
}
App app{{.port = "0", .documentRoot = "ui"}};
app.cppFunction("quote.calculate", [](int count) {
if (count < 1 || count > 1000)
throw std::invalid_argument("Invalid quantity");
return count * 25;
});
webfront::testing::JasmineTest tests{app};
app.show();
app.shutdown();
return tests.exitCode();
}在 CMake 中注册测试
把 WebFront 1.3.0 的代码放在子目录 WebFront/ 中。将 main.cpp 和下面的 CMakeLists.txt 放在项目根目录;页面和测试保持前面给出的路径。
FRONTEND 参数检查所需的引擎是否已启用。C++ 程序也显式选择了这个引擎。配置时,辅助函数会下载并校验 jasmine-core 7.0.2。
测试规格文件是普通的 JavaScript 脚本。如果其源码使用 TypeScript 或模块,请先编译。
cmake_minimum_required(VERSION 3.31)
project(Quote LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 23)
set(WEBFRONT_EMBED_WKWEBVIEW ON CACHE BOOL "" FORCE)
add_subdirectory(WebFront)
enable_testing()
add_executable(Quote main.cpp)
target_link_libraries(Quote PRIVATE WebFront::WebFront)
webfront_use_native_window(Quote)
webfront_add_jasmine_test(NAME QuoteJourney TARGET Quote
SPECS tests/ui/quote.spec.js tests/ui/native.spec.js
PROGRAMS "$<TARGET_FILE:Quote>"
FRONTEND WKWebView TIMEOUT 60)
set_tests_properties(QuoteJourney PROPERTIES
WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}")运行测试并解读结果
用下面的命令构建应用并运行 CTest。测试的 JSON 报告写在 build/webfront-jasmine/QuoteJourney/ 下。
以下情况测试会失败:断言不成立、使用了聚焦的测试组、执行的规格数为零、缺少报告、应用出错或超时。可以把 75 改为 74 来验证,然后恢复测试。
在 Linux 上,请选择 CEF 或 WebKitGTK 并安装 xvfb-run。在 Windows 上,请选择 WebView2。系统浏览器不适用于这种测试方式。依赖准备好之后,执行测试不需要访问公共网络。
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --parallel 2
ctest --test-dir build --output-on-failure选择更多流程
一个有用的流程测试从已知状态出发,检查可观察到的结果。在生命游戏中,可以选择一个图案、推进一代、检查网格,再重置模拟。在设置工具中,可以修改一个值、保存、重新加载页面并检查是否已保存。
每个用例都应建立自己的初始条件,并等待明确的完成信号。C++ 错误和连接断开应各有单独的用例。键盘输入、焦点、原生对话框和视觉呈现需要额外的检查。
同时测试原生程序
WebFront 允许 Jasmine 测试规格运行所有者在 PROGRAMS 中列出的程序。下面的 tests/ui/native.spec.js 使用授权的路径,检查在示例 main.cpp 中加入的 --version 模式。它测试编译后的程序,而不会再打开一个窗口。
程序直接运行,不经过 Shell,参数按字面传递。status、exitCode、stdout 和 stderr 用于区分不同结果。非零退出或超时是可以断言的结果;未经授权的请求会使 Promise 被拒绝。没有 PROGRAMS 时,对 webFrontHost 的调用会被拒绝。
以 XML 转 JSON 的转换工具为例,可以用 withTemp 准备私有空间,用 writeFile 放入输入,用 readText 读取输出。测试规格随后把生成的文档与预期结果比较。这些空间在测试后会被清理;限制和强制停止的情况见指南。
describe('the native application', () => {
it('reports its version without opening a window', async () => {
const [program] = await webFrontHost.programs();
const result = await webFrontHost.run({
program, args: ['--version'], timeoutMs: 5000
});
expect(result.status).toBe('exited');
expect(result.exitCode).toBe(0);
expect(result.stdout).toContain('Quote 1.0');
});
});保存流程截图
下面的用例放在 tests/ui/quote.spec.js 的 describe 组中,使用其中的 until 函数。断言总价之后,webFrontCapture.screenshot 把窗口的网页内容保存到构建目录下的 webfront-jasmine/QuoteJourney/captures/quote-75.png。
record(name, {seconds, framesPerSecond}) 生成一组编号的 PNG 图片,可以再用外部编码器转换为视频。截图属于插桩测试构建,MCP 检查不会公开它们,它们本身也不构成视觉一致性测试。
指南记录了各平台的验证情况:涉及原生程序的浏览器流程已在 Linux 上验证;进程运行器的单元测试还覆盖了 Windows 和 macOS。这并不意味着所有引擎上的完整流程都已通过验证。
it('documents the calculated quotation', async () => {
await window.appReady;
document.getElementById('quantity').value = '3';
document.getElementById('calculate').click();
await until(() => !document.getElementById('calculate').disabled);
expect(document.getElementById('total').textContent).toBe('75');
await webFrontCapture.screenshot('quote-75');
});检验理解