为什么我能';t从jasmine中的javascript函数访问全局变量
我用的是茉莉花 我在为什么我能';t从jasmine中的javascript函数访问全局变量,javascript,jasmine,Javascript,Jasmine,我用的是茉莉花 我在SpecRunner.html中声明了一个全局变量global_song(我可以从chrome控制台访问它,因此它是真正的全局变量),其中包括我试图将全局_song连接到“应该能够播放歌曲”的脚本: 为什么它不能访问全局\u song变量 更新:expect(player.currentlyPlayingSong).toEqual(global_-song)有效,而它(“应该能够播放歌曲”+global_-song无效。您在哪里定义了global_-song?如果您在befo
SpecRunner.html
中声明了一个全局变量global_song(我可以从chrome控制台访问它,因此它是真正的全局变量),其中包括我试图将全局_song连接到“应该能够播放歌曲”的脚本:
为什么它不能访问全局\u song
变量
更新:
expect(player.currentlyPlayingSong).toEqual(global_-song)
有效,而它(“应该能够播放歌曲”+global_-song
无效。您在哪里定义了global_-song?如果您在beforeach()函数中这样做,此行为就像描述块中的代码一样有意义(它试图定义您的it()函数)在beforeach()之前执行,如其他SO答案中所述。我想您的全局歌曲是在执行
player.play(song);
这就是为什么它在测试中不能作为it
的第一个参数使用,并且在expect(player.currently playingsong.toEqual(global_-song)
断言中执行player.play
后可用
尝试将简单分配添加到global_song
中,并与player.play分开,以验证在player.play执行之前是否可用:
window.global_song = 'value'
只需看一看该示例,就可以说明问题的主要候选对象:
function foo(){
window['bar'] = 'bar';
}
console.log(window.bar); // Undefined
foo(); // now window contain bar variable.
console.log(window.bar); // 'bar'
我不使用Jasmine,只是想知道全局歌曲变量是否在该语句执行时声明。您的变量global\u song
是否在Jasmine程序运行之前声明?否则它不会被定义。请参阅我的更新:expect(player.currentlyPlayingSong)。toEqual(global\u song)在(“应该能够播放歌曲”+全球歌曲不能work@user310291你使用karma作为测试跑步者吗?@AndriyIvaneyko不,我不知道karma yetas我说我在SpecRunner.html中定义了global_song,证明我可以从chrome控制台Expect(player.currentlyPlayingSong)访问这个变量。toEqual(global_song)工作,而它(“应该能够播放歌曲”)“+全球歌不起作用
function foo(){
window['bar'] = 'bar';
}
console.log(window.bar); // Undefined
foo(); // now window contain bar variable.
console.log(window.bar); // 'bar'