怫然的英文译语怎么说-六级听力在线练习


2023年4月6日发(作者:新东方英语口语培训)

Jasmine使⽤教程

前⾔

随着前端开发的复杂度与⽇俱增,前端⼯程师写出来的JS代码变得越来越庞⼤,从⽽使项⽬变的臃肿,维护的成本及难度不断加⼤,协作迭代开

发已经很难保证代码的功能性不被破坏。所以在这种情况下,考虑引⼊⼀款前端的单元测试框架,来为代码保驾护航是⼀件很重要的事情。

什么是单元测试

或许⼤家在看⼀些产品书籍的时候,当介绍⼀个项⽬时,会不由⾃主说到测试。⽐如,单元测试,函数测试,或是TDD,BDD等测试模式。

那究竟什么是单元测试呢?

单元测试,单元,测试。

什么是单元(unit)?单元就是相对独⽴的功能模块。⼀个完整的、模块化的程序,都是由许多单元构成,单元完成⾃⼰的任务、然后与其它单元

进⾏交互,最终协同完成整个程序功能。

什么是测试?测论语十二章翻译最简短 试就是测试,判断测试对象对于某个特定的输⼊有没有预期的输出。

所以什么是单元测试?就是对构成程序的每个单元进⾏测试(⼤雾)。⼯程上的⼀个共识是,如果程序的每个模块都是正确的、模块与模块的连接

是正确的、那么程序基本上就会是正确的。

所以单元测试就是这么⼀个概念,⼀种努⼒保证构成程序的每个模块的正确性,从⽽保证整个程序的正确性的⽅法论。

说⽩了,单元测试的⽬的就是来保证你写的JS模块能够完成任务并且没有出现bug,如果你的代码在单元测试的过程中,需要引⼊多个模块时,

这说明你测试的主体模块的耦合度相对⽐较⾼,也就意味着你要重构代码了。

单元测试的模式

单元测试的模式基本分为:TDD和BDD。

TDD全称是Test-drivendevelopment,即测试驱动开发。

TDD的原理是在开发功能代码之前,先编写单元测试⽤例代码,测试代码确定需要编写什么产品代码。

TDD的基本思路就是通过测试来推动整个开发的进⾏,但测试驱动开发并不只是单纯的测试⼯作,⽽是把需求分析,设计,质量控制量化的过

程。

TDD⾸先考虑使⽤需求(对象、功能、过程、接⼝等),主要是编写测试⽤例框架对功能的过程和接⼝进⾏设计,⽽测试框架可以持续进⾏验

证。

通常的TDD测试步骤是:

先写测试

再写代码

测试

重构

通过

BDD全称是:Behavior-Drivendevelopment,即⾏为驱动开发。

BDD的应⽤场景就是给⼀些QA⼯程师使⽤的,他⽤他的语⾔和你进⾏交流,即他会进⾏⼀些测试⽤例,然后如果通过则说明,他已经信赖你

了。

⽽BDD与TDD的主要区别是,使得⾮程序⼈员也能参与到测试⽤例的编写中来,⼤⼤降低了客户、⽤户、项⽬管理者与开发者之间来回翻译的

成本。所以BDD更加注重业务需求⽽不是技术,⽽⽬前在⼤部分公司⾥⾯,通常使⽤的是BDD测试。⽽我们本⽂的重点就是讲⼀款BDD模式的测

试框架,那就是Jasmine。

什么是Jasmine

⾸先,Jasmine是⼀款JavaScript测试框架,它不依赖于其他任何JavaScript组件。它有⼲净清晰的语法,让您可以很简单的写出测试代码。

其次,Jasmine官⽹介绍⾥⾯开篇第⼀句话是“Jasmineisabehavior-drivendevelopmentframeworkfortestingJavaScriptcode.”,

主要的意思就是说它是⼀款BDD模式的测试框架,也就是⾏为驱动开发,同样它是⼀种敏捷软件开发的技术。

BDD更像是⼀种团队的约定,javascript单元测试,也许对于你本⼈(开发该脚本的前端)意义不是特别突出,但对于

整个团队,整个项⽬来说就是⼀种财富

如何使⽤Jasmine

1、在项⽬根⽬录中,初始化

npminit

2、⽬录结构:

-src

-

-test

-

3、安装karma+jasmine相关包

npminstall-gkarma-cli

npminstallkarmakarma-jasminekarma-chrome-launcherjasmine-core--save-dev

4、开启Karma

karmastart

image

⼿动打开Chrome,输⼊localhost:9876

image

5、初始化karma

karmainit

image

说明:

1.测试框架:我们当然选jasmine

2.是否添加插件

3.选择浏览器:我们选Chrome

4.测试⽂件路径设置,⽂件可以使⽤通配符匹配,⽐如*.js匹配指定⽬录下所有的js⽂件(实际操作中发现该路径是⽂件的相对

路径,详见下⾯我给出的实际测试配置及说明)

5.在测试⽂件路径下,需要排除的⽂件

6.是否允许Karma监测⽂件,yes表⽰当测试路径下的⽂件变化时,Karma会⾃动测试

以下是的完整内容:

//Karmaconfiguration

//GeneratedonWedNov16201614:26:14GMT+0800(中国标准时间)

s=function(config){

({

//basepaththatwillbeusedtoresolveallpatterns(,exclude)

basePath:\'\',

//frameworkstouse

//availableframeworks:/browse/keyword/karma-adapter

frameworks:[\'jasmine\'],

//listoffiles/patternstoloadinthebrowser

files:[

\'src/**/*.js\',

\'test/**/*.js\'

],

//listoffilestoexclude

exclude:[],

//preprocessmatchingfilesbeforeservingthemtothebrowser

//availablepreprocessors:/browse/keyword/karma-preprocessor

preprocessors:{

},

//testresultsreportertouse

//possiblevalues:\'dots\',\'progress\'

//availablereporters:/browse/keyword/karma-reporter

reporters:[\'progress\'],

//webserverport

p静夜思古诗意思全解 ort:9876,

//enable/disablecolorsintheoutput(reportersandlogs)

colors:true,

//leveloflogging

//possiblevalues:_DISABLE||_ERROR||_WARN||_INFO||_DEBUG

logLevel:_INFO,

//enable/disablewatchingfileandexecutingtestswheneveranyfilechanges

autoWatch:true,

//startthesebrowsers

//availablebrowserlaunchers:/browse/keyword/karma-launcher

browsers:[\'Chrome\'],

//ContinuousIntegrationmode

//iftrue,Karmacapturesbrowsers,runsthetestsandexits

singleRun:false,

//Concurrencylevel

//howmanybrowsershouldbestartedsimultaneous

concurrency:Infinity

})

}

内容:

functionreverse(name){

if(name===\'AAA\')return\'BBB\';

(\"\").reverse().join(\"\");

}

内容:

describe(\"全部变量,定义测试\",阅微草堂笔记译文 function(){

beforeEach(function(){

});

afterEach(function(){

});

it(\"reverseword\",function(){

expect(\"DCBA\").toBe(reverse(\"ABCD\"));

});

});

启动karma:

karmastart

因为我们在配置⾥设置了在Chrome中测试,因此karma会⾃动启动Chrome实例,并运⾏测试⽤例:

image

如果我们点击图中的debug按钮,进⼊并按F12打开开发者⼯具,选择Console窗⼝,我们将能看到jasmine的执⾏⽇志

image

这个时候,说明我们已经部署成功,并且可以进⾏测试⽤例编写。

代码覆盖率

如果你还想查看测试的代码覆盖率,我们可以安装karma-coverage插件,安装命令为:

npminstallkarma-coverage--save-dev

修改,增加覆盖率的配置:

preprocessors:{

\'src/**/*.js\':[\'coverage\']

}

reporters:[\'progress\',\'coverage\']

//add

coverageReporter:{

type:\'html\',

dir:\'coverage/\'

}

变动如下:

在reporters中增加coverage

preprocessors中指定js⽂件

添加coverageReporter节点,将覆盖率报告类型type设置为html,输⼊⽬录dir指定到你希望的⽬录中

启动Karma

karmastart

(执⾏命令后,在配置⽂件coverageReporter节点中指定的dir中,我们将找到⽣成的覆盖率报告,karma-coverage还⽣成了⼀层⼦晏子简介 ⽂件

夹,对应于执⾏测试的浏览器+版本号+操作系统版本)

image

使⽤jasmine-html

HTML

JasmineSpecRunnerv2.4.1

myFirstJasmineTest

/*

Createdbylaixiangranon2015/12/15.

jasmine测试脚本

*/

(function(){

/*

jasmine基本语法介绍:

describe(string,function):可以理解为是⼀个测试集或者测试包(官⽅称之为suite),主要功能是⽤来划分单元测试的,describe是可以嵌套使⽤的

参数string:描述测试包的信息

参数function:测试集的具体实现,可包含任意代码

it(string,function):测试⽤例(官⽅称之为spec)

参数string:描述测试⽤例的信息

参数function:测试⽤例的具体实现,可包含任意代码

expect:断⾔表达式

从以下例⼦可知:

1、每个测试⽂件中可以包含多个describe

2、每个describe中可以包含多个it

3、每个it中可以包含多个expect

4、describe可嵌套使⽤

*/

describe(\"JasmineTest1\",function(){

it(\"aspecwithanexpectation\",function(){

expect(1).toBe(1);

expect(1===1).toBe(true);

expect(\"a\").(\"b\");

});

it(\"anotherspecincurrentsuite\",function(){

expect(true).toBe(true);

});

});

describe(\"JasmineTest2\",function(){

it(\"nothing\",function(){

});

});

describe(\"JasmineTest3\",function(){

describe(\"JasmineTest4\",function(){

it(\"b等于b\",function(){

expect(\"b\").toBe(\"b\");

});

it(\"1===1是正确的\",function(){

expect(1===1).toBe(true);

});

});

});

});

/*

*expect的匹配器

**/

describe(\"Includedmatchers:\",function(){

//\"toBe\"基本类型判断

it(\"The\'toBe\'matchercompareswith===\",function(){

vara=12;

varb=a;

expect(a).toBe(b);

expect(a).(null);

});

//\"toEqual\"除了能判断基本类型(相当于\"toBe\"),还能判断对象

describe(\"The\'toEqual\'matcher\",function(){

//基本类型判断

it(\"worksforsimpleliteralsandvariables\",function(){

vara=12;

expect(a).toEqual(12);

});

//对象判断

it(\"shouldworkforobjects\",function(){

varfoo={

a:12,

b:34

};

varbar={

a:12,

b:34

};

expect(foo).toEqual(bar);

});

});

//\"toMatch\"使⽤正则表达式判断

it(\"The\'toMatch\'matcherisforregularexpressions\",function(){

varmessage=\"foobarbaz\";

expect(message).toMatch(/bar/);

expect(message).toMatch(\"bar\");

expect(message).h(/quux/);

});

//\"toBeDefined\"判断是否定义

it(\"The\'toBeDefined\'matchercomparesagainst\'undefined\'\",function(){

vara={

foo:\"foo\"

};

expect().toBeDefined();

expect().fined();

});

//\"toBeUndefined\"判断是否是undefined,与\"toBeDefined\"相反

it(\"The\'toBeUndefined\'matchercomparesagainst\'undefined\'\",function(){

vara={

foo:\"foo\"

};

expect().defined();

expect().toBeUndefined();

});

//\"toBeNull\"判断是否为null

it(\"The\'toBeNull\'matchercomparesagainstnull\",function(){

vara=null;

varfoo=\"foo\";

expect(null).toBeNull();

expect(a).toBeNull();

expect(foo).ll();

});

//\"toBeTruthy\"判断是否是true

it(\"The\'toBeTruthy\'matcherisforbooleancastingtesting\",function(){

vara,foo=\"foo\";

expect(foo).toBeTruthy();

expect(a).uthy();

expect(true).toBeTruthy();

});

});

//\"toBeFalsy\"判断是否是false

it(\"The\'toBeFalsy\'matcherisforbooleancastingtesting\",function(){

vara,foo=\"foo\";

expect(a).toBeFalsy();

expect(foo).lsy();

expect(false).toBeFalsy();

});

//\"toContain\"判断数组是否包含(可判断基本类型和对象)

it(\"The\'toContain\'matcherisforfindinganiteminanArray\",function(){

vara=[\"foo\",\"bar\",\"baz\"];

varb=[{foo:\"foo\",bar:\"bar\"},{baz:\"baz\",bar:\"bar\"}];

expect(a).toContain(\"bar\");

expect(a).ain(\"quux\");

expect(b).toContain({foo:\"foo\",bar:\"bar\"});

expect(b).ain({foo:\"foo\",baz:\"baz\"});

});

//\"toBeLessThan\"判断值类型的⼤⼩,结果若⼩则为True(也可以判断字符及字符串,以ascii码的⼤⼩为判断依据)

it(\"The\'toBeLessThan\'matcherisformathematicalcomparisons\",function(){

varpi=3.1415926,

e=2.78;

expect(e).toBeLessThan(pi);

expect(pi).ssThan(e);

expect(\"a\").toBeLessThan(\"b\");

expect(\"b\").ssThan(\"a\");

});

//\"toBeGreaterThan\"判断值类型的⼤⼩,结果若⼤则为True,与toBeLessThan相反(也可以判断字符及字符串,以ascii码的⼤⼩为判断依据)

it(\"The\'toBeGreaterThan\'matcherisformathematicalcomparisons\",function(){

varpi=3.1415926,

e=2.78;

expect(水光潋滟晴方好描写的是哪里的景色 pi).toBeGreaterThan(e);

expect(e).eaterThan(pi);

expect(\"a\").eaterThan(\"b\");

expect(\"b\").toBeGreaterThan(\"a\");

});

//\"toBeCloseTo\"判断数字是否相似(第⼆个参数为⼩数精度,默认为2位)

it(\"The\'toBeCloseTo\'matcherisforprecisionmathcomparison\",function(){

vara=1.1;

varb=1.5;

varc=1.455;

vard=1.459;

expect(a).toBeCloseTo(b,0);

expect(a).oseTo(c,1);

expect(c).toBeCloseTo(d);

});

//\"toThrow\"判断是否抛出异常

it(\"The\'toThrow\'matcherisfortestingifafunctionthrowsanexception\",function(){

varfoo=function(){

return1+2;

};

varbar=function(){

returna+1;

};

expect(foo).w();

expect(bar).toThrow();

});

//\"toThrowError\"判断是否抛出了指定的错误

it(\"The\'toThrowError\'matcherisfortestingaspecificthrownexception\",function(){

varfoo=function(){

thrownewTypeError(\"foobarbaz\");

};

expect(foo).toThrowError(\"foobarbaz\");

expect(foo).toThrowError(/bar/);

expect(foo).toThrowError(TypeError);

expect(foo).toThrowError(TypeError,\"foobarbaz\");

});

});

/*

*\"fail\"函数能使⼀个测试⽤例失败,参数为⾃定义的失败信息

**/

describe(\"Aspecusingthefailfunction\",function(){

varfoo=function(x,callBack){

if(x){

if(x){

callBack();

}

};

it(\"shouldnotcallthecallBack\",function(){

foo(false,function(){

fail(\"Callbackhasbeencalled\");

});

});

});

/*

Jasmine允许在执⾏测试集/测试⽤例的开始前/结束后做⼀些初始化/销毁的操作。

Setup⽅法:

beforeAll:每个suite(即describe)中所有spec(即it)运⾏之前运⾏

beforeEach:每个spec(即it)运⾏之前运⾏

Teardown⽅法:

afterAll:每个suite(即describe)中所有spec(即it)运⾏之后运⾏

afterEach:每个spec(即it)运⾏之后运⾏

**/

varglobalCount;

describe(\"SetupandTeardownsuite1\",function(){

varsuiteGlobalCount;

vareachTestCount;

beforeAll(function(){

globalCount=0;

suiteGlobalCount=0;

eachTestCount=0;

});

afterAll(function(){

suiteGlobalCount=0;

});

beforeEach(function(){

globalCount++;

suiteGlo魏晋南北朝 balCount++;

eachTestCount++;

});

afterEach(function(){

eachTestCount=0;

});

it(\"Spec1\",function(){

expect(globalCount).toBe(1);

expect(suiteGlobalCount).toBe(1);

expect(eachTestCount).toBe(1);

});

it(\"Spec2\",function(){

expect(globalCount).toBe(2);

expect(suiteGlobalCount).toBe(2);

expect(eachTestCount).toBe(1);

});

});

describe(\"SetupandTeardownsuite2\",function(){

beforeEach(function(){

globalCount+=2;

});

it(\"Spec1\",function(){

expect(globalCount).toBe(4);

});

});

/*

*在beforeEach-it-afterEach中,还可以使⽤this关键字定义变量。需要注意的是,使⽤this关键字声明的变量,仅在beforeEach-it-afterEach这个过程中传递

**/

**/

describe(\"Test\'this\'\",function(){

beforeEach(function(){

unt=unt||0;

unt++;

});

afterEach(function(){

//unt=0;//⽆论是否有这⾏,结果是⼀样的,因为this指定的变量只能在每个spec的beforeEach/it/afterEach过程中传递

});

it(\"Spec1\",function(){

expect(unt).toBe(1);

});

it(\"Spec2\",function(){

expect(unt).toBe(1);

});

});

/*

在实际项⽬中,需要由于发布的版本需要选择测试⽤例包,xdescribe和xit能很⽅便的将不包含在版本中的测试⽤例排除在外。

不过xdescribe和xit略有不同:

xdescribe:该describe下的所有it将被忽略,Jasmine将直接忽略这些it,因此不会被运⾏

xit:运⾏到该it时,挂起它不执⾏

**/

xdescribe(\"Testxdescribe\",function(){

it(\"Spec1\",function(){

expect(1).toBe(1);

});

it(\"Spec2\",function(){

expect(2).toBe(2);

});

});

describe(\"Testxit\",function(){

it(\"Spec1\",function(){

expect(1).toBe(1);

});

xit(\"Spec2\",function(){

expect(2).toBe(1);

});

xit(\"Spec3\",function(){

expect(3).toBe(3);

});

});

/*

*Spy⽤来追踪函数的调⽤历史信息(是否被调⽤、调⽤参数列表、被请求次数等)。Spy仅存在于定义它的describe和it⽅法块中,并且每次在spec执⾏完之后被销毁。

*当在⼀个对象上使⽤spyOn⽅法后即可模拟调⽤对象上的函数,此时对所有函数的调⽤是不会执⾏实际代码的。

*两个Spy常⽤的expect:

*toHaveBeenCalled:函数是否被调⽤

*toHaveBeenCalledWith:调⽤函数时的参数

**/

describe(\"Aspy\",function(){

varfoo,bar=null;

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

}

};

spyOn(foo,\"setBar\");//在foo对象上添加spy

//此时调⽤foo对象上的⽅法,均为模拟调⽤,因此不会执⾏实际的代码

(123);//调⽤foo的setBar⽅法

(456,\"anotherparam\");

});

it(\"tracksthatthespywascalled\",function(){

it(\"tracksthatthespywascalled\",function(){

expect().toHaveBeenCalled();//判断foo的setBar是否被调⽤

});

it(\"tracksalltheargumentsofitscalls\",function(){

expect().toHaveBeenCalledWith(123);//判断被调⽤时的参数

expect().toHaveBeenCalledWith(456,\"anotherparam\");

});

it(\"stopsallexecutiononafunction\",function(){

expect(bar).toBeNull();//由于是模拟调⽤,因此bar值并没有改变

});

});

/*

*spyOn().rough(),告诉Jasmine我们除了要完成对函数调⽤的跟踪,同时也需要执⾏实际的代码。

**/

describe(\"Aspy,whenconfiguredtocallthrough\",function(){

varfoo,bar,fetchedBar;

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

},

getBar:function(){

returnbar;

}

};

spyOn(foo,\"getBar\").rough();//这⾥使⽤了callThrough,这时所有的函数调⽤为真实的执⾏

spyOn(foo,\"setBar\").rough();

(123);

fetchedBar=();

});

it(\"tracksthatthespywascalled\",function(){

expect().toHaveBeenCalled();

});

it(\"shouldnoteffectotherfunctions\",function(){

expect().toHaveBeenCalledWith(123);

expect(bar).toEqual(123);//由于是真实调⽤,因此bar有了真实的值

});

it(\"whencalledreturnstherequestedvalue\",function(){

expect(fetchedBar).toEqual(123);//由于是真实调⽤,fetchedBar也有了真实的值

});

});

/*

*spyOn().Value(),由于Spy是模拟函数的调⽤,因此我们也可以强制指定函数的返回值。

**/

describe(\"Aspy,whenconfiguredtofakeareturnvalue\",function(){

varfoo,bar,fetchedBar;

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

},

getBar:function(){

returnbar;

}

};

spyOn(foo,\"getBar\").Value(745);//这将指定getBar⽅法返回值为745

(123);

fetchedBar=();

});

it(\"tracksthatthespywascalled\",function(){

expect().toHaveBeenCalled();

});

it(\"shouldnoteffectotherfunctions\",function(){

it(\"shouldnoteffectotherfunctions\",function(){

expect(bar).toEqual(123);

});

it(\"whencalledreturnstherequestedvalue\",function(){

expect(fetchedBar).toEqual(745);

});

});

/*

*spyOn().ke(),

*与returnValue相似,callFake则更进⼀步,直接通过指定⼀个假的⾃定义函数来执⾏。这种⽅式⽐returnValue更灵活,我们可以任意捏造⼀个函数来达到我们的测试要求。

**/

describe(\"Aspy,whenconfiguredwithanalternateimplementation\",function(){

varfoo,bar,fetchedBar;

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

},

getBar:function(){

returnbar;

}

};

spyOn(foo,\"getBar\").ke(function(){

return1001;

});

(123);

fetchedBar=();

});

it(\"tracksthatthespywascalled\",function(){

expect().toHaveBeenCalled();

});

it(\"shouldnoteffectotherfunctions\",function(){

expect(bar).toEqual(123);

});

it(\"whencalledreturnstherequestedvalue\",function(){

expect(fetchedBar).toEqual(1001);

});

});

/*

*spyOn().rror(),模拟异常的抛出

**/

describe(\"Aspy,whenconfiguredtothrowanerror\",function(){

varfoo,bar;

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

}

};

spyOn(foo,\"setBar\").rror(\"quux\");

});

it(\"throwsthevalue\",function(){

expect(function(){

(123)

}).toThrowError(\"quux\");

});

});

/*

*spyOn().(),回复到原始的spyOn()⽅法

**/

describe(\"Aspy\",function(){

varfoo,bar=null;

beforeEach(function(){

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

},

getBar:function(){

returnbar;

}

};

spyOn(foo,\"setBar\").rough();//标记1

spyOn(foo,\"getBar\").Value(999);//标记2

});

it(\"cancallthroughandthenstubinthesamespec\",function(){

(123);

expect(bar).toEqual(123);

vargetValue=();

expect(getValue).toEqual(999);

();//相当于\"标记1\"中的代码变为了spyOn(foo,\"setBar\")

();//相当于\"标记2\"中的代码变为了spyOn(foo,\"getBar\")

bar=null;

(123);

expect(bar).toBe(null);

expect().toHaveBeenCalled();//函数调⽤追踪并没有被重置

getValue=();

expect(getValue).toEqual(undefined);

expect().toHaveBeenCalled();//函数调⽤追踪并没有被重置

});

});

/*

*其他追踪属性:

calls:对于被Spy的函数的调⽤,都可以在calls属性中跟踪。

.():被Spy的函数⼀旦被调⽤过,则返回true,否则为false;

.():返回被Spy的函数的被调⽤次数;

.r(index):返回被Spy的函数的调⽤参数,以index来指定参数;

.s():返回被Spy的函数的所有调⽤参数;

.():返回calls的上下⽂,这将返回当前calls的整个实例数据;

.cent():返回calls中追踪的最近⼀次的请求数据;

.():返回calls中追踪的第⼀次请求的数据;

.object:当调⽤all(),mostRecent(),first()⽅法时,返回对象的object属性返回的是当前上下⽂对象;

.():重置Spy的所有追踪数据;

**/

describe(\"Aspy\",function(){

varfoo,bar=null;

beforeEach(function(){

foo={

setBar:function(value){

bar=value;

}

};

spyOn(foo,\"setBar\");

});

//.():被Spy的函数⼀旦被调⽤过,则返回true,否则为false;

it(\"tracksifitwascalledatall\",function(){

expect(()).toEqual(false);

();

expect(()).toEqual(true);

});

//.():返回被Spy的函数的被调⽤次数;

it(\"tracksthenumberoftimesitwascalled\",function(){

expect(()).toEqual(0);

();

();

expect(()).toEqual(2);

});

});

//.r(index):返回被Spy的函数的调⽤参数,以index来指定参数;

it(\"trackstheargumentsofeachcall\",function(){

(123);

(456,\"baz\");

expect(r(0)).toEqual([123]);

expect(r(1)).toEqual([456,\"baz\"]);

});

//.s():返回被Spy的函数的所有调⽤参数;

it(\"trackstheargumentsofallcalls\",function(){

(123);

(456,\"baz\");

expect(s()).toEqual([[123],[456,\"baz\"]]);

});

//.():返回calls的上下⽂,这将返回当前calls的整个实例数据;

it(\"canprovidethecontextandargumentstoallcalls\",function(){

(123);

expect(()).toEqual([{object:foo,args:[123],returnValue:undefined}]);

});

//.cent():返回calls中追踪的最近⼀次的请求数据;

it(\"hasashortcuttothemostrecentcall\",function(){

(123);

(456,\"baz\");

expect(cent()).toEqual({object:foo,args:[456,\"baz\"],returnValue:undefined});

});

//.():返回calls中追踪的第⼀次请求的数据;

it(\"hasashortcuttothefirstcall\",function(){

(123);

(456,\"baz\");

expect(()).toEqual({object:foo,args:[123],returnValue:undefined});

});

//.object:当调⽤all(),mostRecent(),first()⽅法时,返回对象的object属性返回的是当前上下⽂对象;

it(\"tracksthecontext\",function(){

varspy=Spy(\"spy\");

varbaz={

fn:spy

};

varquux={

fn:spy

};

(123);

(456);

expect(().object).toBe(baz);

expect(cent().object).toBe(quux);

});

//.():重置Spy的所有追踪数据;

it(\"canbereset\",function(){

(123);

(456,\"baz\");

expect(()).toBe(true);

();

expect(()).toBe(false);

});

});

/*

Spy()

*假如没有函数可以追踪,我们可以⾃⼰创建⼀个空的Spy。

*创建后的Spy功能与其他的Spy⼀样:跟踪调⽤、参数等,但该Spy没有实际的代码实现,这种⽅式经常会⽤在对JavaScript中的对象的测试。

**/

describe(\"Aspy,whencreatedmanually\",function(){

varwhatAmI;

beforeEach(function(){

whatAmI=Spy(\"whatAmI\");

whatAmI(\"I\",\"am\",\"a\",\"spy\");

});

});

it(\"isnamed,whichhelpsinerrorreporting\",function(){

expect(ty()).toEqual(\"whatAmI\");

});

it(\"tracksthatthespywascalled\",function(){

expect(whatAmI).toHaveBeenCalled();

});

it(\"tracksitsnumberofcalls\",function(){

expect(()).toEqual(1);

});

it(\"tracksalltheargumentsofitscalls\",function(){

expect(whatAmI).toHaveBeenCalledWith(\"I\",\"am\",\"a\",\"spy\");

});

it(\"allowsaccesstothemostrecentcall\",function(){

expect(cent().args[0]).toEqual(\"I\");

});

});

/*

SpyObj()

*如果需要spy模拟多个函数调⽤,可以向SpyObj中传⼊⼀个字符串数组,它将返回⼀个对象,

*你所传⼊的所有字符串都将对应⼀个属性,每个属性即为⼀个Spy。

**/

describe(\"Multiplespies,whencreatedmanually\",function(){

vartape;

beforeEach(function(){

tape=SpyObj(\'tape\',[\'play\',\'pause\',\'stop\',\'rewind\']);

();

();

(0);

});

it(\"createsspiesforeachrequestedfunction\",function(){

expect().toBeDefined();

expect().toBeDefined();

expect().toBeDefined();

expect().toBeDefined();

});

it(\"tracksthatthespieswerecalled\",function(){

expect().toHaveBeenCalled();

expect().toHaveBeenCalled();

expect().toHaveBeenCalled();

expect().BeenCalled();

});

it(\"tracksalltheargumentsofitscalls\",function(){

expect().toHaveBeenCalledWith(0);

});

});

/*

*()

*以构造器或者类名作为参数,Jasmine将判断期望值和真实值的构造器是否相同,若相同则返回true。

**/

describe(\"\",function(){

it(\"matchesanyvalue\",function(){

expect({}).toEqual((Object));

expect(12).toEqual((Number));

});

describe(\"whenusedwithaspy\",function(){

it(\"isusefulforcomparingarguments\",function(){

varfoo=Spy(\"foo\");

foo(12,function(){

returntrue;

});

expect(foo).toHaveBeenCalledWith((Number),(Function));

expect(foo).toHaveBeenCalledWith((Number),(Function));

});

});

});

/*

*ng()

*判断只要不是null或undefined的值,若不是则返回true。

**/

describe(\"ng\",function(){

it(\"matchesanything\",function(){

expect(1).toEqual(ng());

});

describe(\"whenusedwithaspy\",function(){

it(\"isusefulwhentheargumentcanbeignored\",function(){

varfoo=Spy(\'foo\');

foo(12,function(){

returnfalse;

});

expect(foo).toHaveBeenCalledWith(12,ng());

});

});

});

/*

*Containing()

*⽤来判断对象中是否存在指定的键值属性对。

**/

describe(\"Containing\",function(){

varfoo;

beforeEach(function(){

foo={

a:1,

b:2,

bar:\"baz\"

};

});

it(\"matchesobjectswiththeexpectkey/valuepairs\",function(){

expect(foo).toEqual(Containing({

bar:\"baz\"

}));

expect(foo).l(Containing({

c:37

}));

});

describe(\"whenusedwithaspy\",function(){

it(\"isusefulforcomparingarguments\",function(){

varcallback=Spy(\"callback\");

callback({

bar:\"baz\"

});

expect(callback).toHaveBeenCalledWith(Containing({

bar:\"baz\"

}));

expect(callback).BeenCalledWith(Containing({

c:37

}));

});

});

});

/*

*ontaining()

*可以⽤来判断数组中是否有期望的值。

**/

describe(\"ontaining\",function(){

varfoo;

beforeEach(function(){

beforeEach(function(){

foo=[1,2,3,4];

}蓦然回首的近义词 );

it(\"matchesarrayswithsomeofthevalues\",function(){

expect(foo).toEqual(ontaining([3,1]));//直接在期望值中使⽤ontaining达到⽬的

expect(foo).l(ontaining([6]));

});

describe(\"whenusedwithaspy\",function(){

it(\"isusefulwhencomparingarguments\",function(){

varcallback=Spy(\"callback\");//创建⼀个空的Spy

callback([1,2,3,4]);//将数组内容作为参数传⼊Spy中

expect(callback).toHaveBeenCalledWith(ontaining([4,2,3]));

expect(callback).BeenCalledWith(ontaining([5,2]));

});

});

});

/*

*Matching()

*⽤来模糊匹配字符串,在Matching中也可以使⽤正则表达式进⾏匹配,使⽤起来⾮常灵活。

**/

describe(\"Matching\",function(){

it(\"matchesasaregexp\",function(){

expect({foo:\"bar\"}).toEqual({foo:Matching(/^bar$/)});

expect({foo:\"foobarbaz\"}).toEqual({foo:Matching(\"bar\")});

});

describe(\"whenusedwithaspy\",function(){

it(\"isusefulforcomparingarguments\",function(){

varcallback=Spy(\"callback\");

callback(\"foobarbaz\");

expect(callback).toHaveBeenCalledWith(Matching(\"bar\"));

expect(callback).BeenCalledWith(Matching(/^bar$/));

});

});

});

/*

*不规则匹配(⾃定义匹配):asymmetricMatch

*某些场景下,我们希望能按照⾃⼰设计的规则进⾏匹配,此时我们可以⾃定义⼀个对象,该对象只要包含⼀个名为asymmetricMatch的⽅法即可。

**/

describe(\"customasymmetry\",function(){

vartester={

asymmetricMatch:function(actual){

varsecondValue=(\",\")[1];

returnsecondValue===\"bar\";

}

};

it(\"divesindeep\",function(){

expect(\"foo,bar,baz,quux\").toEqual(tester);

});

describe(\"whenusedwithaspy\",function(){

it(\"isusefulforcomparingarguments\",function(){

varcallback=Spy(\"callback\");

callback(\"foo,bar,baz\");

expect(callback).toHaveBeenCalledWith(tester);

});

});

});

/*

*()⽤来模拟操纵时间。

*要想使⽤(),先调⽤().install告诉Jasmine你想要在spec或者suite操作时间,当你不需要使⽤时,务必调⽤().uninstall来恢复时间状态

*

*⽰例中使⽤().tick(milliseconds)来控制时间前进,本例中出现了三种时间控制⽅式:

*setTimeout:定期执⾏⼀次,当().tick()的时间超过了timeout设置的时间时触发

*setInterval:定期循环执⾏,每当().tick()的时间超过了timeout设置的时间时触发

*mockDate:模拟⼀个指定⽇期(当不提供基准时间参数时,以当前时间为基准时间)

**/

describe(\"ManuallytickingtheJasmineClock\",function(){

describe(\"ManuallytickingtheJasmineClock\",function(){

vartimerCallback;

beforeEach(function(){

timerCallback=Spy(\"timerCallback\");

().install();

});

afterEach(function(){

().uninstall();

});

it(\"causesatimeouttobecalledsynchronously\",function(){

setTimeout(function(){

timerCallback();

},100);

expect(timerCallback).BeenCalled();

().tick(101);

expect(timerCallback).toHaveBeenCalled();

});

it(\"causesanintervaltobecalledsynchronously\",function(){

setInterval(function(){

timerCallback();

},100);

expect(timerCallback).BeenCalled();

().tick(101);

expect(()).toEqual(1);

().tick(50);

expect(()).toEqual(1);

().tick(50);

expect(()).toEqual(2);

});

describe(\"MockingtheDateobject\",function(){

it(\"mockstheDateobjectandsetsittoagiventime\",function(){

varbaseTime=newDate();

().mockDate(baseTime);

().tick(50);

expect(newDate().getTime()).toEqual(e()+50);

});

});

});

/*

*Jasmine可以⽀持spec中执⾏异步操作。

*当调⽤beforeEach,it和afterEach时,函数可以包含⼀个可选参数done,当spec执⾏完毕之后,调⽤done通知Jasmine异步操作已执⾏完毕。

*

*另外补充⼀点,如果需要设置全局的默认超时时间,可以设置T_TIMEOUT_INTERVAL的值,

*当异步执⾏时间超过设置的执⾏超时时间js将会报错。

**/

describe(\"Asynchronousspecs\",function(){

varvalue;

beforeEach(function(done){

setTimeout(function(){

value=0;

done();

},1);

});

//在上⾯beforeEach的done()被执⾏之前,这个测试⽤例不会被执⾏

it(\"shouldsupportasyncexecutionoftestpreparationandexpectations\",function(done){

value++;

expect(value).toBeGreaterThan(0);

done();//执⾏完done()之后,该测试⽤例真正执⾏完成

});

//Jasmine异步执⾏超时时间默认为5秒,超过后将报错

describe(\"longasynchronousspecs\",function(){

varoriginalTimeout;

beforeEach(function(){

originalTimeout=T_TIMEOUT_INTERVAL;

originalTimeout=T_TIMEOUT_INTERVAL;

//设置全局的默认超时时间

T_TIMEOUT_INTERVAL=6000;

});

it(\"takesalongtime\",function(done){

setTimeout(function(){

done();

},4000);

});

//如果要调整指定⽤例的默认的超时时间,可以在beforeEach,it和afterEach中传⼊⼀个时间参数

//it(\"takesalongtimeforthisspec\",function(done){

//setTimeout(function(){

//done();

//},6000);

//},7000);

afterEach(function(){

T_TIMEOUT_INTERVAL=originalTimeout;

});

});

});

}());

image

更多推荐

jasmin是什么意思min在线翻译读音例句