原创:Jasmine中describe和it_wangmiaoyan的博客-CSDN博客_describe js
上文中提到PlayerSpec.js,我们用notepad打开内容如下:
describe("Player", function() {
var player;
var song;
beforeEach(function() {
player = new Player();
song = new Song();
});
it("should be able to play a Song", function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(song);
//demonstrates use of custom matcher
expect(player).toBePlaying(song);
});
describe("when song has been paused", function() {
beforeEach(function() {
player.play(song);
player.pause();
});
it("should indicate that the song is currently paused", function() {
expect(player.isPlaying).toBeFalsy();
// demonstrates use of 'not' with a custom matcher
expect(player).not.toBePlaying(song);
});
it("should be possible to resume", function() {
player.resume();
expect(player.isPlaying).toBeTruthy();
expect(player.currentlyPlayingSong).toEqual(song);
});
});
// demonstrates use of spies to intercept and test method calls
it("tells the current song if the user has made it a favorite", function() {
spyOn(song, 'persistFavoriteStatus');
player.play(song);
player.makeFavorite();
expect(song.persistFavoriteStatus).toHaveBeenCalledWith(true);
});
//demonstrates use of expected exceptions
describe("#resume", function() {
it("should throw an exception if song is already playing", function() {
player.play(song);
expect(function() {
player.resume();
}).toThrowError("song is already playing");
});
});
});
我们可以看到其中有describe、beforeEach、it等函数
describe
describe("Player", function()
{
/* tests */
});
describe是可以嵌套使用的,我们可以理解为一个大故事是由多个小故事组成的,从PlagerSpec.js中我们也可以看到有嵌套使用的describe函数。
it("should be able to play a Song", function() {
player.play(song);
expect(player.currentlyPlayingSong).toEqual(song);
});
在我看来,it可以理解为故事中人物的行为
describe和it函数的字符串参数是很重要的。如果描述得当的话,你的测试可以将一个完整的测试场景以自然语言的形式表达出来,形成文档。
describe和it都属于JavaScript函数,所以JavaScript的作用域规则也适用于此。
用java中学过的全局变量与局部变量的概念来说,我们可以把describe类别为一个class,把it类比于里面的方法,在describe中声明的变量即全局变量,在它里面的所以的it中都可以使用。而it中声明的变量为局部变量,只在此it内部有效。
beforeEach
-如果你用过Junit,或者python+selenium,就会发现里面都会有Setup,Teardown ,也就是俗称的安装和拆卸。
我们在执行用例之前,通常都需要做大量的铺垫,例如准备测试数据,建立测试场景,这些为了成功测试而做的准备工作成为Test Fixture。测试完之后需要释放资源。这些大量的重复的工作我们可以放在setup和teardown中,减少代码的冗余。在测试运行之前先运行setup,测试结束后运行teardown。
在Jasmine中有四个全局函数用于安装和拆卸,如下
beforeEach [在每一个测试用例(it块)执行之前都执行一遍beforeEach 函数]
afterEach [在每一个测试用例(it块)执行之后都执行一遍afterEach 函数]
beforeAll [在测试套件(describe块)中所有测试用例执行之前执行一遍beforeAll函数]
afterAll [在测试套件(describe块)中所有测试用例执行之后执行一遍afterAll函数]
describe中代码与拆装卸载以及it的执行顺序是怎样的?下一节我们举例来说明
————————————————
版权声明:本文为CSDN博主「wangmiaoyan」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wangmiaoyan/article/details/79026647