計算機(jī)軟件及應(yīng)用JAVASCRIPT驅(qū)動開發(fā)小教程BY KISSY TEAM_第1頁
計算機(jī)軟件及應(yīng)用JAVASCRIPT驅(qū)動開發(fā)小教程BY KISSY TEAM_第2頁
計算機(jī)軟件及應(yīng)用JAVASCRIPT驅(qū)動開發(fā)小教程BY KISSY TEAM_第3頁
計算機(jī)軟件及應(yīng)用JAVASCRIPT驅(qū)動開發(fā)小教程BY KISSY TEAM_第4頁
計算機(jī)軟件及應(yīng)用JAVASCRIPT驅(qū)動開發(fā)小教程BY KISSY TEAM_第5頁
已閱讀5頁,還剩40頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

UnderstandingJavaScriptTesting2021-10-14Why?Cross-browserissues.跨瀏覽器問題;Thepossibilityforcausinganunforeseenproblemissimplytoogreat.不可預(yù)見的問題的存在性很大;How?TeststrategyEnd-to-endtest:Big,Powerful,Convincing;Slow,In-exact,High-maintenance;UnittestsSmall,Quick,Focused,Resilient;Limited;Componentteststhebalancebetweenmanyfasttestandafewslowtests;TestMethods-測試腳本+模擬環(huán)境;測試腳本+驅(qū)動真實(shí)瀏覽器;直接在瀏覽器中Unittest;模擬環(huán)境下進(jìn)行Unittest;UnitTestingBreakcodeintologicalchucksfortesting.將整段代碼分成多個邏輯塊來測試;Focusononemethodatatime同一時間內(nèi)只關(guān)注一個方法;-支持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;傳統(tǒng)單元測試,如YUI3TestCase-函數(shù)名組織: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的現(xiàn)有工具: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的重點(diǎn)是通過與利益相關(guān)者的討論取得對預(yù)期的軟件行為的清醒認(rèn)識。它通過用自然語言書寫非程序員可讀的測試用例擴(kuò)展了測試驅(qū)動開發(fā)方法。行為驅(qū)動開發(fā)人員使用混合了領(lǐng)域中統(tǒng)一的語言的母語語言來描述他們的代碼的目的。這讓開發(fā)著得以把精力集中在代碼應(yīng)該怎么寫,而不是技術(shù)細(xì)節(jié)上,而且也最大程度的減少了將代碼編寫者的技術(shù)語言與商業(yè)客戶、用戶、利益相關(guān)者、工程管理者等的領(lǐng)域語言之間來回翻譯的代價。Jasmine實(shí)戰(zhàn)Specs:說明,使用it(description,fn)來描述;it('shouldincrementavariable',function(){//一段有意義的描述,加一個要執(zhí)行的系列動作

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

Case,使用describe()函數(shù);describe('Calculator',function(){it('canaddanumber',function(){...});it('hasmultiplysomenumbers',function(){...});});Suites的名字一般為你要測試的模塊/組件/應(yīng)用名字;Suites中的每個Spec只執(zhí)行一次,一個Suites,一個作用域,里面的Spec共享;NestedDescribes支持嵌套的Describes;beforeEach(fn)/afterEach(fn)對應(yīng)于以前的setUp(fn)/tearDown(fn),在每個spec執(zhí)行之前/之后執(zhí)行;this.after(fn)在特定的某個spec執(zhí)行之后執(zhí)行.沒有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()設(shè)置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.用于模擬傳參,回調(diào)函數(shù),異步請求/行為監(jiān)測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,事件回調(diào)等,就是針對在未來某個點(diǎn)上會發(fā)生的行為.runs()阻塞執(zhí)行,就像是直接調(diào)用一樣;多個runs()共享作用域.waits(timeout)等待多長時間后再執(zhí)行下面的語句.waitsFor(function,optionalmessage,optionaltimeout)直到function返回true才執(zhí)行下去.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);});});});其他相關(guān)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捕獲瀏覽器,通過命令通知效勞器進(jìn)行測試.然后每個被捕獲的瀏覽器運(yùn)行tests,并將結(jié)果返回;優(yōu)點(diǎn):-運(yùn)行測試不需要手工跟瀏覽器進(jìn)行交互;-可在多臺機(jī)器上運(yùn)行,包括移動設(shè)備,允許任意復(fù)雜的測試;-測試非常快速,因?yàn)椴恍枰僮鱀OM,且多個瀏覽器中是同時進(jìn)行;-現(xiàn)已支持異步請求測試;缺點(diǎn):-JavaScriptrequiredtoruntestsisslightlymoreadvanced,andmaycauseaprobleminoldbrowsers;使用JSTestDriver目錄結(jié)構(gòu):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運(yùn)行測試: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)結(jié)合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,就可以看到j(luò)stestdriver.gifcmd下,java-jarJsTestDriver-1.2.2.jar--testsall小結(jié)一下TestSwarm眾包測試TestSwarmprovidesdistributedcontinuousintegrationtestingforJavaScript.why?--JavaScriptTestingDoesNotScaleTheprimarygoalofTestSwarmistotakethecomplicated,andtime-consuming,processofrunningJavaScripttestsuitesinmultiplebrowsersandtogrosslysimplifyit.ItachievesthisgoalbyprovidingallthetoolsnecessaryforcreatingacontinuousintegrationworkflowforyourJavaScriptproject.中心效勞器,客戶端連接至他,job提交到這里;客戶端是一個testrunner實(shí)例,加載在瀏覽器中.testrunner每30秒中請求效勞器是否有新的testsuites需要運(yùn)行,如果有,就執(zhí)行(放在一個iframe中),其結(jié)果發(fā)送到效勞器上.沒有就睡眠等待;一個job包含testsuites和browsers(需要在哪些瀏覽器中進(jìn)行測試),運(yùn)行至少一次.私有成員測試Approach1:Don'tTestPrivateMethods-如果你需要對私有成員做測試時

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論