Why I can't access global variable from javascript function in jasmine

你。 提交于 2019-12-12 19:32:01

问题


I'm using Jasmine standalone https://github.com/jasmine/jasmine/releases

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);
});

Why it cannot access global_song variable ?

Update : expect(player.currentlyPlayingSong).toEqual(global_song) works whereas it("should be able to play Song " + global_song doesn't work.


回答1:


Where have you defined global_song? If you did that in the beforeEach() function this behaviour would make sense as the code in the describe block (which attempts to define your it() function) gets executed before the beforeEach() as described in this other SO answer.




回答2:


Well i suppose your global_song created after executing of

player.play(song);

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.

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'


来源:https://stackoverflow.com/questions/35963143/why-i-cant-access-global-variable-from-javascript-function-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!