SlideShare una empresa de Scribd logo
1 de 37
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar 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
 

Similar 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

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Último (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 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