为什么我无法从jasmine中的javascript函数访问全局变量 [英] Why I can't access global variable from javascript function in jasmine
问题描述
我正在使用Jasmine独立版 https://github.com/jasmine/jasmine/releases
I'm using Jasmine standalone https://github.com/jasmine/jasmine/releases
我在 SpecRunner.html
中声明了一个全局变量global_song(我可以从chrome控制台访问它,所以它是真正全球化的,其中包括我试图将global_song连接到应该能够播放歌曲的脚本:
I have declared a global variable global_song in SpecRunner.html
(I can access it from chrome console so it's truly global) which includes script where I am trying to concatenate global_song to "should be able to play Song " :
it("should be able to play Song " + global_song, function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(global_song);
//demonstrates use of custom matcher
expect(player).toBePlaying(song);
});
为什么它无法访问 global_song
变量?
Why it cannot access global_song
variable ?
更新: expect(player.currentlyPlayingSong).toEqual(global_song)
有效,而 it(应该能够播放歌曲+ global_song
不起作用。
Update : expect(player.currentlyPlayingSong).toEqual(global_song)
works whereas it("should be able to play Song " + global_song
doesn't work.
推荐答案
嗯,我认为你的 global_song
是在执行
Well i suppose your global_song
created after executing of
player.play(song);
这种方式在测试中不可用作<$ c的第一个参数$ c> it 并在 expect(player.currentlyPlayingSong).toEqual(global_song)<执行
player.play
后可用/ code>断言。
That's way it's not available in test as first parameter of it
and available after executing player.play
in expect(player.currentlyPlayingSong).toEqual(global_song)
assertion.
尝试将简单赋值添加到 global_song
与 player.play
在执行 player.play
之前验证它是否可用:
Try to add simple assignment to global_song
separatelly from player.play
to verify that it's available before player.play
executed:
window.global_song = 'value'
只需查看该示例,以说明问题的主要候选人:
Just take a look on that sample to illustrate the main possible candidate of problem:
function foo(){
window['bar'] = 'bar';
}
console.log(window.bar); // Undefined
foo(); // now window contain bar variable.
console.log(window.bar); // 'bar'
这篇关于为什么我无法从jasmine中的javascript函数访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!