SlideShare uma empresa Scribd logo
1 de 37
Baixar para ler offline
Testing
with

          1
Self introduction


Jonathan Waller




                  2
Content

What is Node.js?

Testing the code

Checking test coverage

Testing the user interface

Pulling it all together



                          3
WHAT IS NODE.JS?

4
What is Node.js?
    example.js
var	
  http	
  =	
  require('http');

http.createServer(function	
  (request,	
  response)	
  {
	
   response.writeHead(200,	
  {'Content-­‐Type':	
  'text/plain'});
	
   response.end('Hello	
  Worldn');
}).listen(8080);

console.log('Server	
  running	
  at	
  http://127.0.0.1:8080/');




    Running it
$	
  node	
  example.js
Server	
  running	
  at	
  http://127.0.0.1:8080/




                                                    5
Node is non-blocking
          Blocking code

var	
  fileContents1	
  =	
  fs.readFileSync('file1.txt');
console.log(fileContents1);

var	
  fileContents2	
  =	
  fs.readFileSync('file2.txt');
console.log(fileContents2);




                0s                                     5s    10s



                                                         6
Node is non-blocking
           Non-blocking code
var	
  callback	
  =	
  function(err,	
  fileContents){
	
      console.log(fileContents);
}

fs.readFile('file1.txt',	
  callback);
fs.readFile('file2.txt',	
  callback);




                 0s                                       5s   10s



                                                           7
$	
  node	
  example.js




                8
TESTING THE CODE

9
Testing the code
                   describe('file.js',	
  function()	
  {
                   	
   describe('functionName',	
  function()	
  {
                   	
   	
   it('action',	
  function()	
  {
                   	
   	
   	
   ...



   MOCHA


                   expect(myObject.id).to.be(undefined);
                   expect(myObject).to.eql({	
  a:	
  'b'	
  })
                   expect(myVariable1).to.be.a('number');
                   expect(myVariable2).to.be.an('array');




  EXPECT.JS

              10
11
TESTING SYNCHRONOUS CODE 1


var	
  fileContents1	
  =	
  fs.readFileSync('file1.txt');
console.log(fileContents1);                                                              SYNC_EXAMPLE.JS
var	
  fileContents2	
  =	
  fs.readFileSync('file2.txt');
console.log(fileContents2);




function	
  readFile1(){
	
   return	
  fs.readFileSync('file1.txt');                                              SYNC_EXAMPLE.JS
}

function	
  readFile2(){
	
   return	
  fs.readFileSync('file2.txt');
}                                                             var	
  sync_example	
  =	
  require(‘./sync_example’);

modules.exports.readFile1	
  =	
  readFile1;
modules.exports.readFile2	
  =	
  readFile2;
                                                                               TEST/SYNC_EXAMPLE.JS


                                                         12
TESTING SYNCHRONOUS CODE 2
function	
  readFile1(){
	
   return	
  fs.readFileSync('file1.txt');                                          SYNC_EXAMPLE.JS
}

function	
  readFile2(){
	
   return	
  fs.readFileSync('file2.txt');
}

modules.exports.readFile1	
  =	
  readFile1;
modules.exports.readFile2	
  =	
  readFile2;



var	
  sync_example	
  =	
  require(‘../sync_example’);
                                                                                  TEST/SYNC_EXAMPLE.JS
describe('sync_example.js',	
  function()	
  {
	
   describe('readFile1',	
  function()	
  {
	
   	
   it('reads	
  the	
  content	
  of	
  the	
  file',	
  function()	
  {
	
   	
   	
   var	
  fileContents1	
  =	
  sync_example.readFile1();
	
   	
   	
   expect(fileContents1.length).to.be.greaterThan(0);
	
   	
   });
	
   });
	
   describe('readFile2',	
  function()	
  {
	
   	
   it('reads	
  the	
  content	
  of	
  the	
  file',	
  function()	
  {
	
   	
   	
   var	
  fileContents2	
  =	
  sync_example.readFile2();
	
   	
   	
   expect(fileContents2.length).to.be.greaterThan(0);
	
   	
   });
	
   });
});

                                                           13
TESTING ASYNCHRONOUS CODE 1


var	
  callback	
  =	
  function(err,	
  fileContents){
	
      console.log(fileContents);                             ASYNC_EXAMPLE.JS
}

fs.readFile('file1.txt',	
  callback);
fs.readFile('file2.txt',	
  callback);




function	
  readFile1(callback){
	
   fs.readFile('file1.txt',	
  callback);                    ASYNC_EXAMPLE.JS
}

function	
  readFile2(callback){
	
   fs.readFile('file2.txt',	
  callback);
}

modules.exports.readFile1	
  =	
  readFile1;
modules.exports.readFile2	
  =	
  readFile2;




                                                          14
TESTING ASYNCHRONOUS CODE 2
function	
  readFile1(callback){
	
   fs.readFile('file1.txt',	
  callback);                                           ASYNC_EXAMPLE.JS
}

function	
  readFile2(callback){
	
   fs.readFile('file2.txt',	
  callback);
}

modules.exports.readFile1	
  =	
  readFile1;
modules.exports.readFile2	
  =	
  readFile2;



describe('async_example.js',	
  function()	
  {
	
   describe('readFile1',	
  function()	
  {                                TEST/ASYNC_EXAMPLE.JS
	
   	
   it('reads	
  the	
  content	
  of	
  the	
  file',	
  function(done)	
  {
	
   	
   	
   async_example.readFile1(function(err,fileContents1){
	
   	
   	
   	
   expect(fileContents1.length).to.be.greaterThan(0);
	
   	
   	
   	
   done();
	
   	
   	
   });
	
   	
   });
	
   });
	
   describe('readFile2',	
  function()	
  {
	
   	
   it('reads	
  the	
  content	
  of	
  the	
  file',	
  function(done)	
  {
	
   	
   	
   async_example.readFile2(function(err,fileContents2){
	
   	
   	
   	
   expect(fileContents2.length).to.be.greaterThan(0);
	
   	
   	
   	
   done();
	
   	
   	
   });
	
   	
   });
	
   });
});
                                                          15
TESTING ASYNCHRONOUS CODE 3



async_example.readFile1(function(err,fileContents1){
	
   expect(fileContents1.length).to.be.greaterThan(0);
	
   done();
});




                                               =
var	
  callback1	
  =	
  function(err,fileContents1){
	
      expect(fileContents1.length).to.be.greaterThan(0);
	
      done();
}
async_example.readFile1(callback1);




                                                   16
$	
  mocha	
  test/example.js	
  -­‐r	
  expect.js




                             17
JSCoverage
 CHECKING TEST COVERAGE




           18
19
Checking test coverage


 JSCoverage
$	
  jscoverage	
  index.js
                                   json-cov




                              20
Checking test coverage

             Instrumenting JS file
$	
  jscoverage	
  index.js




             Running tests (Running the instrumented code)
$	
  mocha	
  test/index.js	
  -­‐R	
  json-­‐cov	
  >	
  coverage.html




                                                                     21
SpookyJS

TESTING THE USER INTERFACE

                             22
UI testing
SpookyJS is a                  SpookyJS

scriptable web testing
framework for Mocha           CasperJS

Wrapper for CasperJs
and PhantomJS

Uses WebKit, so
                              WEBKIT
supports client-side
Javascript


                         23
var	
  Spooky	
  =	
  require('spooky');

var	
  spooky	
  =	
  new	
  Spooky(
	
      {
                                                                                                   SAMPLE SPOOKY SCRIPT
	
      	
      child:	
  {
	
      	
      	
      port:	
  8080,
	
      	
      	
      script:	
  './lib/bootstrap.js',	
  //Loads	
  casperJS
	
      	
      	
      spooky_lib:	
  './node_modules'
	
      	
      }
	
      },	
  function	
  (err,	
  error,	
  response)	
  {
	
      	
  
	
      	
      if	
  (err	
  ||	
  error)	
  {
	
      	
      	
      var	
  e	
  =	
  new	
  Error('Failed	
  to	
  initialize	
  SpookyJS');
	
      	
      	
      e.details	
  =	
  err	
  ||	
  error;
	
      	
      	
      throw	
  e;
	
      	
      }	
  

	
     	
     spooky.on('error',	
  function	
  (e)	
  {console.error(e);});
	
     	
     spooky.on('console',	
  function	
  (line)	
  {console.log(line);});

	
     	
     spooky.start();

	
     	
     spooky.then(function	
  (){
	
     	
     	
   this.echo('Hello,	
  this	
  is	
  SpookyJS');
	
     	
     });

	
     	
     spooky.open('http://www.google.com/');

	
     	
     spooky.then(function	
  ()	
  {
	
     	
     	
   this.echo('Now	
  viewing:	
  '	
  +	
  this.getCurrentUrl());
	
     	
     });

	
     	
     spooky.run();
	
     }
);
                                                                       24
var	
  util	
  =	
  require('util');
var	
  expect	
  =	
  require('expect.js');
describe("Test	
  that	
  SpookyJS	
  is	
  working",	
  function	
  ()	
  {
	
   var	
  context	
  =	
  {};
                                                                                                    TEST/FRONTEND.JS
	
   var	
  hooks	
  =	
  require('../util/hooks');
	
     before(hooks.before(context));
	
     describe('Test	
  that	
  SpookyJS	
  can	
  navigate	
  to	
  Google',	
  function	
  ()	
  {
	
     	
   it('navigates	
  to	
  google.com,	
  and	
  returns	
  the	
  current	
  url',	
  function	
  (done)	
  {
	
     	
     	
     context.spooky.start();

	
     	
     	
     context.spooky.then(function	
  (){
	
     	
     	
     	
   this.echo('Hello,	
  this	
  is	
  SpookyJS');
	
     	
     	
     });

	
     	
     	
     context.spooky.open('http://www.google.com/');

	
     	
     	
     context.spooky.then(function	
  ()	
  {
	
     	
     	
     	
   this.echo(this.getCurrentUrl());
	
     	
     	
     });
	
     	
     	
     function	
  onConsole(line)	
  {
	
     	
     	
     	
   if	
  (line	
  ===	
  'http://www.google.com/')	
  {
	
     	
     	
     	
   	
      context.spooky.removeListener('console',	
  onConsole);
	
     	
     	
     	
   	
      done();
	
     	
     	
     	
   	
      return;
	
     	
     	
     	
   }
	
     	
     	
     }
	
     	
     	
     context.spooky.on('console',	
  onConsole);
	
     	
     	
     context.spooky.run();

	
               	
   });
	
  	
  	
  	
  });
	
  	
  	
  	
  after(hooks.after(context));
});

                                                                  25
$	
  mocha	
  test/frontend/example.js	
  -­‐r	
  expect.js




                              26
$	
  make	
  test

  PULLING IT ALL TOGETHER




            27
Make: Folder structure




testbackend:
	
   @mocha	
  $$(find	
  test/backend	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  spec


...など
                                                              28
Testing the backend
              Makefile
testbackend:
	
   @./node_modules/.bin/mocha	
  $$(find	
  test/backend	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  spec




              Run tests
 $	
  make	
  testbackend



                                                                  29
Checking test coverage
                      Makefile
coverage:
	
    @echo	
  'Checking	
  test	
  code	
  coverage...'

	
         #Cleaning	
  up
	
         @rm	
  -­‐rf	
  _src-­‐with-­‐coverage/	
  &&	
  rm	
  -­‐rf	
  _test-­‐with-­‐coverage/
	
  
	
         #Instrumenting	
  code
	
         @./node_modules/jscoverage/jscoverage	
  src	
  _src-­‐with-­‐coverage

	
         #Creating	
  tests	
  for	
  instrumented	
  code
	
         @cp	
  -­‐r	
  test	
  _test-­‐with-­‐coverage
	
         @find	
  _test-­‐with-­‐coverage	
  -­‐name	
  '*.js'	
  -­‐exec	
  sed	
  -­‐i	
  ''	
  's//src///_src-­‐with-­‐coverage//g'	
  "{}"	
  ;

	
         #Running	
  tests...
	
         @./node_modules/.bin/mocha	
  $$(find	
  _test-­‐with-­‐coverage	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  html-­‐cov	
  >	
  coverage.html

	
         #Cleaning	
  up
	
         @rm	
  -­‐rf	
  _src-­‐with-­‐coverage/	
  &&	
  rm	
  -­‐rf	
  _test-­‐with-­‐coverage/

	
         @echo	
  'Done.	
  Result	
  written	
  to	
  coverage.html.'




                      Check test coverage
       $	
  make	
  coverage


                                                                                                  30
31
Testing the frontend

              Makefile
test:
	
   @./node_modules/.bin/mocha	
  $$(find	
  test/frontend	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  spec




              Run tests
 $	
  make	
  testfrontend




                                                                  32
Makefile

testbackend:
	
   @./node_modules/.bin/mocha	
  $$(find	
  test/backend	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  spec	
  
testfrontend:
	
   @./node_modules/.bin/mocha	
  $$(find	
  test/frontend	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  spec	
  

coverage:
	
   @echo	
  'Checking	
  test	
  code	
  coverage...'
	
   ...
	
   @echo	
  'Done.	
  Result	
  written	
  to	
  coverage.html.'

test:
	
   @./node_modules/.bin/mocha	
  $$(find	
  test/	
  -­‐name	
  "*.js")	
  -­‐r	
  expect.js	
  -­‐R	
  spec	
  

all:	
  test	
  coverage
	
     @echo	
  'Tested	
  frontend	
  and	
  backend.	
  Coverage	
  doc	
  saved	
  to	
  coverage.html.'




               Run all tests
$	
  make	
  test



               Run all tests + show test coverage
$	
  make	
  all
                                                                   33
Summary

Node.js is Javascript on the server.

Unit testing with Mocha + Expect.js

Checking coverage with JSCoverage

User interface testing with SpookyJS

Running everything with Make



                        34
Thank you
ありがとうございました



     35
Contact Jonathan


@jonwaller

facebook.com/jonwaller0

gplus.to/jonwaller
                          www.jonwaller.net/ja/




                     36
References
Node.js

http://nodejs.org/

Unit testing (Mocha)

http://visionmedia.github.com/mocha/

Test coverage

http://tjholowaychuk.com/post/18175682663/mocha-test-coverage

User interface testing

http://casperjs.org/

https://github.com/WaterfallEngineering/SpookyJS

Other useful stuff

https://npmjs.org/ - Learn about commonly used node packages

http://jenkins-ci.org/ - Set up continuous integration (e.g. Automatically testing when you commit)




                                                   37

Mais conteúdo relacionado

Mais procurados

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydneyjulien.ponge
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7Dongho Cho
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programingwahyuseptiansyah
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module DevelopmentJay Harris
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Readingkishima7
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Всеволод Струкчинский: Node.js
Всеволод Струкчинский: Node.jsВсеволод Струкчинский: Node.js
Всеволод Струкчинский: Node.jsYandex
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineMovel
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The LandingHaci Murat Yaman
 
Deterministic simulation testing
Deterministic simulation testingDeterministic simulation testing
Deterministic simulation testingFoundationDB
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 

Mais procurados (20)

Software Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW SydneySoftware Testing - Invited Lecture at UNSW Sydney
Software Testing - Invited Lecture at UNSW Sydney
 
React, Redux and es6/7
React, Redux and es6/7React, Redux and es6/7
React, Redux and es6/7
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing201913046 wahyu septiansyah network programing
201913046 wahyu septiansyah network programing
 
Java
JavaJava
Java
 
devday2012
devday2012devday2012
devday2012
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module Development
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Dalvik Source Code Reading
Dalvik Source Code ReadingDalvik Source Code Reading
Dalvik Source Code Reading
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Learning Dtrace
Learning DtraceLearning Dtrace
Learning Dtrace
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Всеволод Струкчинский: Node.js
Всеволод Струкчинский: Node.jsВсеволод Струкчинский: Node.js
Всеволод Струкчинский: Node.js
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Introduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy CresineIntroduction to ES6 with Tommy Cresine
Introduction to ES6 with Tommy Cresine
 
Node.js System: The Landing
Node.js System: The LandingNode.js System: The Landing
Node.js System: The Landing
 
Deterministic simulation testing
Deterministic simulation testingDeterministic simulation testing
Deterministic simulation testing
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 

Semelhante a Testing with Node.js

Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to ProtractorJie-Wei Wu
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryAlexandre Morgaut
 
NodeJs
NodeJsNodeJs
NodeJsdizabl
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023Laurence Svekis ✔
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfadinathassociates
 

Semelhante a Testing with Node.js (20)

Introduction to Protractor
Introduction to ProtractorIntroduction to Protractor
Introduction to Protractor
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
NoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love StoryNoSQL and JavaScript: a Love Story
NoSQL and JavaScript: a Love Story
 
NodeJs
NodeJsNodeJs
NodeJs
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?wtf is in Java/JDK/wtf7?
wtf is in Java/JDK/wtf7?
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JAVA SE 7
JAVA SE 7JAVA SE 7
JAVA SE 7
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
JS everywhere 2011
JS everywhere 2011JS everywhere 2011
JS everywhere 2011
 
NodeJS
NodeJSNodeJS
NodeJS
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
What`s new in Java 7
What`s new in Java 7What`s new in Java 7
What`s new in Java 7
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
 

Último

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Testing with Node.js

  • 3. Content What is Node.js? Testing the code Checking test coverage Testing the user interface Pulling it all together 3
  • 5. What is Node.js? example.js var  http  =  require('http'); http.createServer(function  (request,  response)  {   response.writeHead(200,  {'Content-­‐Type':  'text/plain'});   response.end('Hello  Worldn'); }).listen(8080); console.log('Server  running  at  http://127.0.0.1:8080/'); Running it $  node  example.js Server  running  at  http://127.0.0.1:8080/ 5
  • 6. Node is non-blocking Blocking code var  fileContents1  =  fs.readFileSync('file1.txt'); console.log(fileContents1); var  fileContents2  =  fs.readFileSync('file2.txt'); console.log(fileContents2); 0s 5s 10s 6
  • 7. Node is non-blocking Non-blocking code var  callback  =  function(err,  fileContents){   console.log(fileContents); } fs.readFile('file1.txt',  callback); fs.readFile('file2.txt',  callback); 0s 5s 10s 7
  • 10. Testing the code describe('file.js',  function()  {   describe('functionName',  function()  {     it('action',  function()  {       ... MOCHA expect(myObject.id).to.be(undefined); expect(myObject).to.eql({  a:  'b'  }) expect(myVariable1).to.be.a('number'); expect(myVariable2).to.be.an('array'); EXPECT.JS 10
  • 11. 11
  • 12. TESTING SYNCHRONOUS CODE 1 var  fileContents1  =  fs.readFileSync('file1.txt'); console.log(fileContents1); SYNC_EXAMPLE.JS var  fileContents2  =  fs.readFileSync('file2.txt'); console.log(fileContents2); function  readFile1(){   return  fs.readFileSync('file1.txt'); SYNC_EXAMPLE.JS } function  readFile2(){   return  fs.readFileSync('file2.txt'); } var  sync_example  =  require(‘./sync_example’); modules.exports.readFile1  =  readFile1; modules.exports.readFile2  =  readFile2; TEST/SYNC_EXAMPLE.JS 12
  • 13. TESTING SYNCHRONOUS CODE 2 function  readFile1(){   return  fs.readFileSync('file1.txt'); SYNC_EXAMPLE.JS } function  readFile2(){   return  fs.readFileSync('file2.txt'); } modules.exports.readFile1  =  readFile1; modules.exports.readFile2  =  readFile2; var  sync_example  =  require(‘../sync_example’); TEST/SYNC_EXAMPLE.JS describe('sync_example.js',  function()  {   describe('readFile1',  function()  {     it('reads  the  content  of  the  file',  function()  {       var  fileContents1  =  sync_example.readFile1();       expect(fileContents1.length).to.be.greaterThan(0);     });   });   describe('readFile2',  function()  {     it('reads  the  content  of  the  file',  function()  {       var  fileContents2  =  sync_example.readFile2();       expect(fileContents2.length).to.be.greaterThan(0);     });   }); }); 13
  • 14. TESTING ASYNCHRONOUS CODE 1 var  callback  =  function(err,  fileContents){   console.log(fileContents); ASYNC_EXAMPLE.JS } fs.readFile('file1.txt',  callback); fs.readFile('file2.txt',  callback); function  readFile1(callback){   fs.readFile('file1.txt',  callback); ASYNC_EXAMPLE.JS } function  readFile2(callback){   fs.readFile('file2.txt',  callback); } modules.exports.readFile1  =  readFile1; modules.exports.readFile2  =  readFile2; 14
  • 15. TESTING ASYNCHRONOUS CODE 2 function  readFile1(callback){   fs.readFile('file1.txt',  callback); ASYNC_EXAMPLE.JS } function  readFile2(callback){   fs.readFile('file2.txt',  callback); } modules.exports.readFile1  =  readFile1; modules.exports.readFile2  =  readFile2; describe('async_example.js',  function()  {   describe('readFile1',  function()  { TEST/ASYNC_EXAMPLE.JS     it('reads  the  content  of  the  file',  function(done)  {       async_example.readFile1(function(err,fileContents1){         expect(fileContents1.length).to.be.greaterThan(0);         done();       });     });   });   describe('readFile2',  function()  {     it('reads  the  content  of  the  file',  function(done)  {       async_example.readFile2(function(err,fileContents2){         expect(fileContents2.length).to.be.greaterThan(0);         done();       });     });   }); }); 15
  • 16. TESTING ASYNCHRONOUS CODE 3 async_example.readFile1(function(err,fileContents1){   expect(fileContents1.length).to.be.greaterThan(0);   done(); }); = var  callback1  =  function(err,fileContents1){   expect(fileContents1.length).to.be.greaterThan(0);   done(); } async_example.readFile1(callback1); 16
  • 17. $  mocha  test/example.js  -­‐r  expect.js 17
  • 19. 19
  • 20. Checking test coverage JSCoverage $  jscoverage  index.js json-cov 20
  • 21. Checking test coverage Instrumenting JS file $  jscoverage  index.js Running tests (Running the instrumented code) $  mocha  test/index.js  -­‐R  json-­‐cov  >  coverage.html 21
  • 23. UI testing SpookyJS is a SpookyJS scriptable web testing framework for Mocha CasperJS Wrapper for CasperJs and PhantomJS Uses WebKit, so WEBKIT supports client-side Javascript 23
  • 24. var  Spooky  =  require('spooky'); var  spooky  =  new  Spooky(   { SAMPLE SPOOKY SCRIPT     child:  {       port:  8080,       script:  './lib/bootstrap.js',  //Loads  casperJS       spooky_lib:  './node_modules'     }   },  function  (err,  error,  response)  {         if  (err  ||  error)  {       var  e  =  new  Error('Failed  to  initialize  SpookyJS');       e.details  =  err  ||  error;       throw  e;     }       spooky.on('error',  function  (e)  {console.error(e);});     spooky.on('console',  function  (line)  {console.log(line);});     spooky.start();     spooky.then(function  (){       this.echo('Hello,  this  is  SpookyJS');     });     spooky.open('http://www.google.com/');     spooky.then(function  ()  {       this.echo('Now  viewing:  '  +  this.getCurrentUrl());     });     spooky.run();   } ); 24
  • 25. var  util  =  require('util'); var  expect  =  require('expect.js'); describe("Test  that  SpookyJS  is  working",  function  ()  {   var  context  =  {}; TEST/FRONTEND.JS   var  hooks  =  require('../util/hooks');   before(hooks.before(context));   describe('Test  that  SpookyJS  can  navigate  to  Google',  function  ()  {     it('navigates  to  google.com,  and  returns  the  current  url',  function  (done)  {       context.spooky.start();       context.spooky.then(function  (){         this.echo('Hello,  this  is  SpookyJS');       });       context.spooky.open('http://www.google.com/');       context.spooky.then(function  ()  {         this.echo(this.getCurrentUrl());       });       function  onConsole(line)  {         if  (line  ===  'http://www.google.com/')  {           context.spooky.removeListener('console',  onConsole);           done();           return;         }       }       context.spooky.on('console',  onConsole);       context.spooky.run();     });        });        after(hooks.after(context)); }); 25
  • 26. $  mocha  test/frontend/example.js  -­‐r  expect.js 26
  • 27. $  make  test PULLING IT ALL TOGETHER 27
  • 28. Make: Folder structure testbackend:   @mocha  $$(find  test/backend  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  spec ...など 28
  • 29. Testing the backend Makefile testbackend:   @./node_modules/.bin/mocha  $$(find  test/backend  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  spec Run tests $  make  testbackend 29
  • 30. Checking test coverage Makefile coverage:   @echo  'Checking  test  code  coverage...'   #Cleaning  up   @rm  -­‐rf  _src-­‐with-­‐coverage/  &&  rm  -­‐rf  _test-­‐with-­‐coverage/     #Instrumenting  code   @./node_modules/jscoverage/jscoverage  src  _src-­‐with-­‐coverage   #Creating  tests  for  instrumented  code   @cp  -­‐r  test  _test-­‐with-­‐coverage   @find  _test-­‐with-­‐coverage  -­‐name  '*.js'  -­‐exec  sed  -­‐i  ''  's//src///_src-­‐with-­‐coverage//g'  "{}"  ;   #Running  tests...   @./node_modules/.bin/mocha  $$(find  _test-­‐with-­‐coverage  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  html-­‐cov  >  coverage.html   #Cleaning  up   @rm  -­‐rf  _src-­‐with-­‐coverage/  &&  rm  -­‐rf  _test-­‐with-­‐coverage/   @echo  'Done.  Result  written  to  coverage.html.' Check test coverage $  make  coverage 30
  • 31. 31
  • 32. Testing the frontend Makefile test:   @./node_modules/.bin/mocha  $$(find  test/frontend  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  spec Run tests $  make  testfrontend 32
  • 33. Makefile testbackend:   @./node_modules/.bin/mocha  $$(find  test/backend  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  spec   testfrontend:   @./node_modules/.bin/mocha  $$(find  test/frontend  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  spec   coverage:   @echo  'Checking  test  code  coverage...'   ...   @echo  'Done.  Result  written  to  coverage.html.' test:   @./node_modules/.bin/mocha  $$(find  test/  -­‐name  "*.js")  -­‐r  expect.js  -­‐R  spec   all:  test  coverage   @echo  'Tested  frontend  and  backend.  Coverage  doc  saved  to  coverage.html.' Run all tests $  make  test Run all tests + show test coverage $  make  all 33
  • 34. Summary Node.js is Javascript on the server. Unit testing with Mocha + Expect.js Checking coverage with JSCoverage User interface testing with SpookyJS Running everything with Make 34
  • 37. References Node.js http://nodejs.org/ Unit testing (Mocha) http://visionmedia.github.com/mocha/ Test coverage http://tjholowaychuk.com/post/18175682663/mocha-test-coverage User interface testing http://casperjs.org/ https://github.com/WaterfallEngineering/SpookyJS Other useful stuff https://npmjs.org/ - Learn about commonly used node packages http://jenkins-ci.org/ - Set up continuous integration (e.g. Automatically testing when you commit) 37