尚未使用Capybara、PhantomJS测试创建DOM对象(TypeError:undefined)

DOM object not yet created (TypeError: undefined) with Capybara, PhantomJS test

本文关键字:对象 TypeError undefined DOM 创建 Capybara 未使用 PhantomJS 测试      更新时间:2023-09-26

我写了一些javascript代码,当点击按钮时,它会执行以下代码(这只是方法的一部分,这行之前和之后都有一些代码。video_id设置在这行上方的某个地方)。

var data_url = $('.BrightcoveExperience').attr('data').replace(/(videoPlayer=)[^'&]+/, '$1' + video_id);

当我在浏览器中测试它时,代码就可以工作了。没有控制台错误。

然而,我的自动黄瓜测试(Capybara with PhantomJS)失败了,并显示以下错误消息

One or more errors were raised in the Javascript code on the page. If you don't care about these errors, you can ignore them by setting js_errors: false in your Poltergeist configuration (see documentation for details).
TypeError: 'undefined' is not an object (evaluating '$('.BrightcoveExperience').attr('data').replace')    

基本上$('.BrightcoveExperience').attr('data')在我的自动测试中返回undefined出于某种原因。

如果我将代码重写为以下内容,测试就会通过

var brightcove_url = $('.BrightcoveExperience').attr('data')
if (typeof brightcove_url !== 'undefined') {
    brightcove_url = brightcove_url.replace(/(videoPlayer=)[^'&]+/, '$1' + video_id);
}

我相信这是由种族状况引起的。不知怎的,在自动测试中,当我点击按钮时,在点击事件代码中,DOM对象$('.BrightcoveExperience')还没有创建。因此,应该引入某种延迟或等待。

但是怎么做呢?

感谢

尝试检查元素的length,如

if($('.BrightcoveExperience').length){
    var brightcove_url = $('.BrightcoveExperience').attr('data')
    // you code here
}