我正在编写一个C ++类ScriptProcess
,用于QML,它充当子进程的接口。所述子进程加载脚本,然后按需执行功能。调用函数时,结果(无论是值还是异常)都是通过信号异步返回的。
import QtQuick 2.5
import QtTest 1.0
import dungeon 1.0
TestCase {
id: test
name: "ScriptProcessTest"
property ScriptProcess session: null
signal exceptionWhenLoadingCode(string type, int line, string message)
SignalSpy {
id: exceptionSpy
target: test
signalName: "exceptionWhenLoadingCode"
}
Component {
id: process
ScriptProcess {
id: script
onExceptionWhenLoadingCode: test.exceptionWhenLoadingCode(type, line, message)
}
}
function startScript(scriptUrl) {
var request = new XMLHttpRequest()
request.open("GET", "data/%1.js".arg(scriptUrl), false)
request.send(null)
return process.createObject(test, {code: request.responseText})
}
function cleanup() {
if (session) {
session.stop()
}
delete session
session = null
}
function test_syntaxErrorInGlobalContextIsReported() {
var count = exceptionSpy.count
session = startScript("syntax-error-in-global-context")
compare(exceptionSpy.count, count + 1)
}
function test_errorThrownInGlobalContextIsReported() {
var count = exceptionSpy.count
session = startScript("error-in-global-context")
compare(exceptionSpy.count, count + 1)
}
}
简而言之,我会做以下事情:
Component
来完成的,其中脚本是通过ScriptProcess.code
属性提供的。我的问题是SignalSpy
被叫exceptionSpy
没有被触发; exceptionSpy.count
始终为零,我不知道为什么。 为什么会这样?我是否误用SignalSpy
或Component
?
答案 0 :(得分:1)
XMLHttpRequest
是异步的,因此您应该将startScript()
更改为:
function startScript(scriptUrl) {
var object = process.createObject(test)
var request = new XMLHttpRequest()
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE)
object.code = request.responseText
}
request.open("GET", "data/%1.js".arg(scriptUrl), false)
request.send(null)
return object
}
由于信号不会马上发出,你必须等待它,而不是在创建对象后立即比较计数:
function test_foo() {
var count = exceptionSpy.count
session = startScript("...")
tryCompare(exceptionSpy, "count", count + 1)
}