我有以下内容:
casper.then(function addToBag(){
this.evaluate(function (){
//register sub method - then emit custom event
mns.msg.sub("/ajax/success/addToCart" + $("[name=productCode]").val(), function (response) {
casper.emit('addToCart.loaded');
});
//trigger add to cart click
$('.product-selection input[type=submit]').click();
});
});
点击触发器激活发射,在事件函数内:
casper.on("addToCart.loaded", function checkAddToCartResponse(){
console.log("Added");
test.assert(true,'Add to cart successful');
}),
但是,它似乎没有运行 - 这是在事件结束时运行测试的正确方法吗?
最佳答案
事件没有发出,因为在页面上下文中(在 evaluate
上下文中)没有 casper
实例。
您需要设置一些标志以指示事件已发出。
casper.then(function addToBag(){
this.evaluate(function (){
//register sub method - then emit custom event
window.casperEventEmitted = null;
mns.msg.sub("/ajax/success/addToCart" + $("[name=productCode]").val(), function (response) {
window.casperEventEmitted = 'addToCart.loaded';
});
//trigger add to cart click
$('.product-selection input[type=submit]').click();
});
});
// wait here
然后等待事件被设置
var timeout = 10000; // msec, some sensible timeout for your event
casper.waitFor(function check() {
return this.getGlobal('casperEventEmitted') == 'addToCart.loaded';
}, function then() {
return this.evaluate(function() {
window.casperEventEmitted = null; // reset for next time
});
this.test.pass("Event triggered");
}, function onTimeout(){
this.test.fail("Event triggered");
}, timeout);
当然,管理队列中的事件而不是单个字符串会更好。
好消息是没有像在 other answer 的情况下发生的自定义事件那样脱离控制流。 .
关于testing - 在事件内部运行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23538004/