Loading

Unit-testing Node.js

reinsbrain

This is a live streamed presentation. You will automatically follow the presenter and see the slide they're currently on.

Unit-testing

by Rein Petersen

Tests-unitarios

Node.js

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

¿Por qué hacemos test-unitarios?

demuestran profesionalismo

confieren su código es seguro de usar

permiten a otros para contribuir a tu código

¿Qué es ‘BDD’?

Behavior-driven-design

desarrollo-orientado-al-­comportamiento

¿Qué es ‘NPM’?

Node Package Manager 

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Herramientas para test-unitarios:

Mocha  mochajs.org

$ npm install -g mocha

Testing Framework ( arnés )

Chai  chaijs.com

$ npm install -g chai

Librería de Aserciónes

$ npm install -g istanbul

Reportes / cobertura código

Sinon.JS  sinonjs.com

$ npm install -g sinon

Espiar / Simular / Imitar

NPM ( npmjs.com )

$ npm run test
$ npm run coverage

Lleve todo junto

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

In case you missed it... el código de ejemplo para esta presentación está disponible en:

 

https://github.com/ReinsBrain/unit-test-bdd-nodejs

Debugging en chrome con node-inspector :

 

$ npm install -g node-inspector

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Configuración del entorno ( package.json )

...
   "scripts": {
      "test": "mocha -w",
      "coverage": "istanbul cover _mocha test --recursive"
   },
   "dependencies": { },
   "devDependencies": {
      "mocha": "latest",
      "chai": "latest",
      "sinon": "latest",
      "sinon-chai": "latest",
      "istanbul": "latest"
   },
...
$ npm run test
$ npm run coverage

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Configuración del entorno ( package.json )

/test/mocha.opts

$ mocha --reporter spec --ui bdd --recursive
$ mocha
$ mocha otraTestCarpeta/testarchivo.js
$ mocha -w
--reporter spec
--ui bdd
--recursive

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Configuración / estructura de archivos testing

index.js

 ↳ lib/validation.js

test/index.js

 ↳ test/lib/validation.js

// index.js
var v = require('lib/validation.js');
// test/lib/index.js
var test = require('../index.js');
var tval = require('lib/validation.js');
// test/lib/validation.js
var test = require('../lib/validation.js');
// lib/validation.js
exports.validate = function ( val ) {
  // TODO: implement this function
  throw new Error('not implemented');
}

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Aserciones (old-school)

/* test/validator_ex1.js */

// basic assertion library provided by NodeJS
var assert = require('assert'); 

console.log( "assert 1==1:", assert.equal(1,1) ); // true
console.log( "assert 1==2:", assert.equal(1,2) ); // false

function malFunc () { throw new Error('booo'); }

console.log( "assert error:", assert.throws( malFunc(), Error ); // true

see https://nodejs.org/api/assert.html - refer test/validator_ex1.js

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Aserciones BDD ("expect" or "suponer")

/* test/validator_ex2.js */

// expect-style assertions with Chaijs
var chai = require("chai");
var expect = chai.expect;

var testval = 1;

console.log( "expect testval==1:", expect(testval).to.equal(1) ); // true
console.log( "expect testval!=2:", expect(testval).to.not.equal(2) ); // true

var fn = function () { throw new Error('booo'); }

console.log( "expect error:", expect(fn).to.throw(Error) ); // true
console.log( "expect no error:", expect(fn).to.not.throw(Error) ); // false

see http://chaijs.com/api/bdd - refer test/validator_ex2.js

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Aserciones BDD (“should” / “deber” y encadenando aserciones)

/* test/validator_ex3.js */

// should-style assertions with Chaijs

var chai = require("chai");
var should = chai.should(); // nota de que 'should' esta instanciada

var testobj = { x:"y" };
var test = testobj.should.be.an('object').with.property('x').that.equals('y');
console.log( "testobj should be object with prop x=='y'", test ); // true

var testdeepobj = { x:{ y:[ { val:"z" } ] } };
var testdeep = testdeepobj.should.have.deep.property("x.y[0].val","z");
console.log("testdeepobj should have deep prop x.y[0].val=='z'", testdeep ); //true

see http://chaijs.com/api/bdd - refer test/validator_ex3.js

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Mocha : Testing Framework (Arnés)

/* test/index.js */

var main = ('../index.js');

describe('main', function () {

  describe('#init', function () {

    it('debe tirar error cuando llamada sin parámetro', function () {
      var fn = function () { index.init(); }; 
      fn.should.throw(Error); // true
    });

  });

});

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Mocha : Testing Modulos

/* test/index.js */

var main = ('../index.js');
var validation;

describe('main', function () {

  describe('__constructor', function () {
    /*…*/
  });

  describe('#validation', function () {
    validation = require('../test/validation.js');
  });

});

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Debugging los tests con node-inspector

$ npm install -g node-inspector

$ node-inspector &

$ mocha --debug-brk

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Live editing in chrome debugger con node-inspector

/.nodeinspectorrc

{
  "save-live-edit":true
}

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Istanbul : Reportes de cobertura

$ npm install -g istanbul

$ istanbul cover _mocha test --recursive

 

A pasear arguments a traves de istanbul a mocha:

$ istanbul cover _mocha test --recursive -- --reporter spec --ui bdd


Encontrar los datos del informe de cobertura en la carpeta test/coverage en formato de html:

test/coverage/lcov-report (tipo de reporter es ‘spec’)


see https://github.com/gotwarlost/istanbul

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Sinon : espias, fakes, stubs, mocks ( simular/imitar )

var sinonChai = require("sinon-chai");

chai.use(sinonChai);
  • Testing-Unitarios para una aplicación de web (REST) con Express (nodejs)
     
  • Estructuración de una aplicación web (REST) para Express (NodeJS)
     
  • Asynchronous Queue Workers on Amazon AWS using NodeJS (Restify)

Test-Unitarios y BDD: Flujo de trabajo usando NodeJS / NPM

Próximas presentaciones de Rein Petersen

Made with Slides.com