计算机软件及应用JAVASCRIPT驱动开发小教程BY KISSY TEAM_第1页
计算机软件及应用JAVASCRIPT驱动开发小教程BY KISSY TEAM_第2页
计算机软件及应用JAVASCRIPT驱动开发小教程BY KISSY TEAM_第3页
计算机软件及应用JAVASCRIPT驱动开发小教程BY KISSY TEAM_第4页
计算机软件及应用JAVASCRIPT驱动开发小教程BY KISSY TEAM_第5页
已阅读5页,还剩40页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

UnderstandingJavaScriptTesting2021-10-14Why?Cross-browserissues.跨浏览器问题;Thepossibilityforcausinganunforeseenproblemissimplytoogreat.不可预见的问题的存在性很大;How?TeststrategyEnd-to-endtest:Big,Powerful,Convincing;Slow,In-exact,High-maintenance;UnittestsSmall,Quick,Focused,Resilient;Limited;Componentteststhebalancebetweenmanyfasttestandafewslowtests;TestMethods-测试脚本+模拟环境;测试脚本+驱动真实浏览器;直接在浏览器中Unittest;模拟环境下进行Unittest;UnitTestingBreakcodeintologicalchucksfortesting.将整段代码分成多个逻辑块来测试;Focusononemethodatatime同一时间内只关注一个方法;-支持UT的已有工具:QUnit,JSUnit,YUITest;UnitTestingFrameworkAssertionFunctionTests/TestCase-test('Atest.',function(){asset(true,'something');asset(false,'something');});-setUp()/tearDown()/setUpPage()

-AsyncTests;setTimeout(function(){},100);TestSuite-addTestPage()/addTestSuite();TestRunner-Responsibleforloadinganexecutingtests;Trace/log-warn()/inform()/debug()3tracinglevels;传统单元测试,如YUI3TestCase-函数名组织:Classic+BDD;-setUp/tearDown;-should:ignore,error,fail;AssertionsMockObjectsAsynchronousTests-wait;-resume;TestSuitesTestRunnerTestReportingvartestCase=newY.Test.Case({name:"TestCaseName",testSpecialValues:function(){Y.Assert.isFalse(false);//passesY.Assert.isTrue(true);//passesY.Assert.isNaN(NaN);//passesY.Assert.isNaN(5/"5");//passesY.Assert.isNotNaN(5);//passesY.Assert.isNull(null);//passesY.Assert.isNotNull(undefined);//passesY.Assert.isUndefined(undefined);//passesY.Assert.isNotUndefined(null);//passesY.Assert.isUndefined({},"Valueshouldbeundefined.");//fails}});BehaviorTestingSimilartounittesting,butbrokenupbytask;Functionallyverysimilartounittesting,usesdifferentterminology;支持BT的现有工具:Screw.Unit,JSSpec,Jasmine如:Jasminecodeisspecification;describe即是TestCase,也是TestSuite;ignore更简单,加上x即可;Matchers可自定义,可覆盖,可添加;-toThrow比YUITest更易用;-expect本身就是一句描述,无需注释;Spiesdescribe('Calculator',function(){varcounter=0it('canaddanumber',function(){counter=counter+2;//counterwas0beforeexpect(bar).toEqual(2);});it('canmultiplyanumber',function(){counter=counter*5;//counterwas2beforeexpect(bar).toEqual(10);});});vartestCase=new({name:"TestCaseName",testSpecialValues:function(){(false);//passes(true);//passes(NaN);//passes(5/"5");//passes(5);//passes(null);//passes(undefined);//passes(undefined);//passes(null);//passes({},"Valueshouldbeundefined.");//fails}});TDDvsBDDTDDisnotabouttesting,butratheraboutdesignandprocess;TDDisadesignactivity;WhyTDD?Makesyouthinkaboutrequiredbehavior;Reducesspeculativecode;Providesdocumentation;Improvesquality;BDDBDD的重点是通过与利益相关者的讨论取得对预期的软件行为的清醒认识。它通过用自然语言书写非程序员可读的测试用例扩展了测试驱动开发方法。行为驱动开发人员使用混合了领域中统一的语言的母语语言来描述他们的代码的目的。这让开发着得以把精力集中在代码应该怎么写,而不是技术细节上,而且也最大程度的减少了将代码编写者的技术语言与商业客户、用户、利益相关者、工程管理者等的领域语言之间来回翻译的代价。Jasmine实战Specs:说明,使用it(description,fn)来描述;it('shouldincrementavariable',function(){//一段有意义的描述,加一个要执行的系列动作

varfoo=0;foo++;});Expecations:期望,存在于spec中,用来描述你期望得到的结果,使用expect()+matchers;it('shouldincrementavariable',function(){varfoo=0; //setuptheworldfoo++; //callyourapplicationcodeexpect(foo).toEqual(1);//passesbecausefoo==1});SuitesSpecs的集合,等于Test

Case,使用describe()函数;describe('Calculator',function(){it('canaddanumber',function(){...});it('hasmultiplysomenumbers',function(){...});});Suites的名字一般为你要测试的模块/组件/应用名字;Suites中的每个Spec只执行一次,一个Suites,一个作用域,里面的Spec共享;NestedDescribes支持嵌套的Describes;beforeEach(fn)/afterEach(fn)对应于以前的setUp(fn)/tearDown(fn),在每个spec执行之前/之后执行;this.after(fn)在特定的某个spec执行之后执行.没有this.before!describe('somesuite',function(){it(function(){varoriginalTitle=window.title;this.after(function(){window.title=originalTitle;});MyWindow.setTitle("newvalue");expect(window.title).toEqual("newvalue");});});xit()/xdescribe()设置spec/describe不可用.Matchersexpect(x).toEqual(y); comparesobjectsorprimitivesxandyandpassesiftheyareequivalentexpect(x).toBe(y); comparesobjectsorprimitivesxandyandpassesiftheyarethesameobjectexpect(x).toMatch(pattern); comparesxtostringorregularexpressionpatternandpassesiftheymatchexpect(x).toBeDefined(); passesifxisnotundefinedexpect(x).toBeNull(); passesifxisnullexpect(x).toBeTruthy(); passesifxevaluatestotrueexpect(x).toBeFalsy(); passesifxevaluatestofalseexpect(x).toContain(y); passesifarrayorstringxcontainsyexpect(x).toBeLessThan(y); passesifxislessthanyexpect(x).toBeGreaterThan(y); passesifxisgreaterthanyexpect(fn).toThrow(e); passesiffunctionfnthrowsexceptionewhenexecutedexpect(x).not.toEqual(y); comparesobjectsorprimitivesxandyandpassesiftheyarenotequivalentMatcher是可以自定义的.使用addMatchers(obj)toBeLessThan:function(expected){returnthis.actual<expected;};beforeEach(function(){this.addMatchers({toBeVisible:function(){returnthis.actual.isVisible();}});});Spiespermitmanyspying,mocking,andfakingbehaviors.用于模拟传参,回调函数,异步请求/行为监测it('shouldspyonaninstancemethodofaKlass',function(){varobj=newKlass();spyOn(obj,'method');obj.method('fooargument');expect(obj.method).toHaveBeenCalledWith('fooargument');varobj2=newKlass();spyOn(obj2,'method');expect(obj2.method).not.toHaveBeenCalled();});AsynchronousSpecs异步测试,测试ajaxapi,事件回调等,就是针对在未来某个点上会发生的行为.runs()阻塞执行,就像是直接调用一样;多个runs()共享作用域.waits(timeout)等待多长时间后再执行下面的语句.waitsFor(function,optionalmessage,optionaltimeout)直到function返回true才执行下去.describe('Spreadsheet',function(){it('shouldcalculatethetotalasynchronously',function(){varspreadsheet=newSpreadsheet();spreadsheet.fillWith(lotsOfFixureDataValues());spreadsheet.asynchronouslyCalculateTotal();waitsFor(function(){returnspreadsheet.calculationIsComplete();},"Spreadsheetcalculationnevercompleted",10000);runs(function(){expect(spreadsheet.total).toEqual(123456);});});});其他相关Automation-FunctionalTesting-SeleniumIDE:-recordsandautomatesactionsperformedbyauser;-AnextensionforFirefoxthatrecordstheactions;-Canplaythembackinallbrowsers(limitedbycross-domainissues);-Primarilyfortestingwebapplications,everyoneshoulduseit;-Browserlaunching-WebDriver;-Waitr;-JsTestDriver;-SeleniumRC;-Server-Side-Ignorethebrowser!Simulateitontheserver-side;-AlmostalwaysusesJava+Rhinotoconstructabrowser;-Someframeworks-Crosscheck:PureJava,evensimulatesbrowserbugs;-Env.js:PureJavaScript,focusesonstandardssupport;-Blueridge:Env.js+Screw.Unit+Rhino;-Distributed-SeleniumGrid-PushSeleniumtestsouttomanymachines(thatyoumanage),simultaneously;-Collectandstoretheresults;-TestSwarm-Pushteststoadistributedswarmofclients;-resultsviewableontheserver;-testswarm;TheScalingProblem-Allneedtoberunforeverycommit,patch,andplugin;-JavaScripttestingdoesn'tscalewell;DistributedTesting-Hubserver;-Clientsconnectandhelpruntest;-AsimpleJavascriptclientthatcanberuninallbrowsers,includingmobilebrowsers;-TestSwarm;JSTestDriver效劳端/客户端,testrunner捕获浏览器,通过命令通知效劳器进行测试.然后每个被捕获的浏览器运行tests,并将结果返回;优点:-运行测试不需要手工跟浏览器进行交互;-可在多台机器上运行,包括移动设备,允许任意复杂的测试;-测试非常快速,因为不需要操作DOM,且多个浏览器中是同时进行;-现已支持异步请求测试;缺点:-JavaScriptrequiredtoruntestsisslightlymoreadvanced,andmaycauseaprobleminoldbrowsers;使用JSTestDriver目录结构:JSTestDriver-jsTestDriver.conf #配置文件-JsTestDriver-1.2.2.jar #核心程序,包含客户端/效劳器-src/ #待测试js源码-src-test/ #js测试脚本配置:server:://localhost:9876load:-src/*.js-src-test/*.js效劳器:java-jarJsTestDriver-1.2.2.jar--port9876浏览器捕获:://localhost:9876/capture运行测试:java-jarJsTestDriver-1.2.2.jar--testsallD:\workspace\Test>java-jarJsTestDriver-1.2.2.jar--testsall--verbose[PASSED]cookieget.testthatitshouldreturnthecookievalueforthegivenname[PASSED]cookieget.testthatitshouldreturnundefinedfornon-existingname[PASSED]cookieset.testthatitshouldsetacookiewithagivennameandvalue[PASSED]cookieremove.testthatitshouldremoveacookiefromthemachine[PASSED]jsonstringify.testthatitshouldconvertanarbitraryvaluetoaJSONstringrepresentation[PASSED]jsonparse.testthatitshouldparseaJSONstringtothenativeJavaScriptrepresentationTotal6tests(Passed:6;Fails:0;Errors:0)(0.00ms)Firefox3.6.10Windows:Run6tests(Passed:6;Fails:0;Errors0)(0.00ms)结合jasmine更改配置为:server:://localhost:9876load:-../github/new/kissy/tests/jasmine/jasmine.js <-../github/jasmine-jstd-adapter/src/JasmineAdapter.js<-../github/new/kissy/src/kissy/*.js-../github/new/kissy/src/cookie/cookie.js-../github/new/kissy/src/cookie/tests/cookie.jsIDE中使用IDEA安装JSTestDriverplugin,重启IDEA,就可以看到jstestdriver.gifcmd下,java-jarJsTestDriver-1.2.2.jar--testsall小结一下TestSwarm众包测试TestSwarmprovidesdistributedcontinuousintegrationtestingforJavaScript.why?--JavaScriptTestingDoesNotScaleTheprimarygoalofTestSwarmistotakethecomplicated,andtime-consuming,processofrunningJavaScripttestsuitesinmultiplebrowsersandtogrosslysimplifyit.ItachievesthisgoalbyprovidingallthetoolsnecessaryforcreatingacontinuousintegrationworkflowforyourJavaScriptproject.中心效劳器,客户端连接至他,job提交到这里;客户端是一个testrunner实例,加载在浏览器中.testrunner每30秒中请求效劳器是否有新的testsuites需要运行,如果有,就执行(放在一个iframe中),其结果发送到效劳器上.没有就睡眠等待;一个job包含testsuites和browsers(需要在哪些浏览器中进行测试),运行至少一次.私有成员测试Approach1:Don'tTestPrivateMethods-如果你需要对私有成员做测试时

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论