Skip to content

Latest commit

 

History

History
474 lines (386 loc) · 23.8 KB

File metadata and controls

474 lines (386 loc) · 23.8 KB

shieldsIO shieldsIO shieldsIO

WideImg

Máster en Programación FullStack con JavaScript y Node.js

JS, Node.js, Frontend, Backend, Firebase, Express, Patrones, HTML5_APIs, Asincronía, Websockets, Testing

Clase 91

Fun Fun Function!

IMG

Testing en la práctica

testing_graph

Las claves

  • Código que verifica el funcionamiento de otro código.
  • Deben poder realizarse de manera automática.
  • Cubrir mayor cantidad de código posible.
  • Independientes entre si.
  • Capaces de ejercutarse infinidad de veces.
  • Pueden agruparse en Test Suites.
  • Uso de colores y mensajes claros.
  • A guide to unit testing in JavaScript

Ejemplo: Versión Browser

// Función
function sumar (p1, p2){
  return p1 + p2;
}

// Test
function testSumar(){
  if (sumar(1, 2) !== 3) {
    document.write('<p style="color: red;">sumar(1, 2) ERROR - No devuelve 3</\p>');
  } else {
    document.write('<p style="color: green;">sumar(1, 2) OK</p>');
  }

  if (sumar("2", 2) !== 4) {
    document.write('<p style="color: red;">sumar("2", 2) ERROR - No devuelve 4</p>');
  } else {
    document.write('<p style="color: green;">sumar("2", 2) OK</p>');
  }
}

Ejemplo: Versión Node.js

const chalk = require('chalk');
const log = console.log;

// Función
function sumar (p1, p2){
  return p1 + p2;
}

// Test
function trueAssert(msg) {
    log(chalk.bgGreen.white(msg))
}

function falseAssert(msg) {
    log(chalk.bgRed.white(msg))
}

function testSumar(){
  if (sumar(1, 2) !== 3) {
    falseAssert("sumar(1, 2) ERROR")
  } else {
    trueAssert("sumar(1, 2) OK")
  }

  if (sumar("2", 2) !== 4) {
    falseAssert('sumar("2", 2) ERROR - No devuelve 4')
  } else {
    trueAssert('sumar("2", 2) OK')
  }
}

testSumar();

Usando console.assert

IMG

const controlador = false;
console.assert(controlador, "\"controlador\" es igual a \"false\"");

Assert Nodejs

const assert = require('assert');

assert.equal(1, 1);     // OK, 1 == 1
assert.equal(1, '1');   // OK, 1 == '1'
assert.equal(1, 2);     // AssertionError: 1 == 2

assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); 
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }

Assertion Testing

Frameworks de testing

BDD/TDD

  • MochaJS - ☕️ simple, flexible, fun javascript test framework for node.js & the browser
  • Jasmine - Simple JavaScript testing framework for browsers and node.js
  • Intern - Intern. Software testing for humans.
  • Chai- BDD / TDD assertion framework for node.js and the browser that can be paired with any testing framework.
  • Ava - 🚀 Futuristic JavaScript test runner

BDD

Test Runners

  • Karma - Spectacular Test Runner for JavaScript
  • Jest - 🃏 Delightful JavaScript Testing.
  • GlaceJS - glace-core is a quick-start functional & unit testing framework based on mocha and extensible with plugins (how plugins work).
  • Apickli - apickl. REST API integration testing framework based on cucumber.js

Spies, Stubs & Mock frameworks

  • Sinon.JS - Test spies, stubs and mocks for JavaScript.
  • JSMockito - Javascript mocking framework inspired by the awesome mockito
  • Apimocker - node.js module to run a simple http server for mock service responses.
  • Rewire - Easy monkey-patching for node.js unit tests
  • Enzyme - JavaScript Testing utilities for React
  • Testdouble - A minimal test double library for TDD with JavaScript

Code analysis

  • ESLint - A fully pluggable tool for identifying and reporting on patterns in JavaScript
  • JsHint - JSHint is a tool that helps to detect errors and potential problems in your JavaScript code
  • JsLint - The JavaScript Code Quality Tool

Performance & stress & load

  • k6 - A modern load testing tool, using Go and JavaScript
  • Artillery - Flexible and powerful toolkit for load and functional testing. HTTP, Socket.io, WebSockets, Kinesis, HLS. Make your systems indestructible! 👩‍💻 🏰
  • LoadComplete - Load Testing Tool for Websites and Web Apps

Security checking

  • OWASP Glue - Application Security Automation
  • OWASP ZAP - The OWASP ZAP core project
  • BeEF - Manipulate the browser exploiting any XSS vulns you find

Reporting

  • ReportPortal.io - AI-powered Test Automation Dashboard
  • Istanbul - Yet another JS code coverage tool that computes statement, line, function and branch coverage with module loader hooks to transparently add coverage when running tests. Supports all JS coverage use cases including unit tests, server side functional tests and browser tests. Built for scale.
  • Blanket - blanket.js is a simple code coverage library for javascript. Designed to be easy to install and use, for both browser and nodejs.
  • Mochawesome - A Gorgeous HTML/CSS Reporter for Mocha.js
  • allure - There are lots of cool testing frameworks for different programming languages. Unfortunately only a few of them can provide good representation of test execution output. The Yandex testing team is working on Allure - an open-source framework designed to create test execution reports that are clear to everyone in the team.

Qunit

Qunit

Las Claves

  • Facil y sencillo
  • Ideal para empezar
  • No contiene muchos plugins
  • Originalmente creado para testear JQuery

Implementacion en browser

fichero index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>QUnit Example</title>
  <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.6.2.css">
</head>
<body>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>
  <script src="https://code.jquery.com/qunit/qunit-2.6.2.js"></script>
  <script src="tests.js"></script>
</body>
</html>

fichero test.js

QUnit.test( "hello test", function( assert ) {
  assert.ok( 1 == "1", "Passed!" );
});

Implementación en Nodejs

npm install --save-dev qunit

Ejemplo

// Función
function sumar (p1, p2){
return p1 + p2;
}

// Test
test("test de la funcion sumar(p1, p2)", function() {
equal(sumar( 1, 2), 3, "1 + 2 = 3" );
notEqual(sumar( "2", 2), "4", " 2(cadena) + 2 != 4(cadena) ");
});

Documentación

API - Main methods

API - Assertions

API - Config

API - Callbacks

API - Async Control

Mocha & Chai

Mocha

Las claves

Las interfaces de Chai

//Assert: 
assert.typeOf( cadena, 'string', 'cadena es un string' );

//Expect: 
expect( cadena ).to.be.a( 'string' );

//Should: 
cadena.should.be.a( 'string' );

Chai plugins

  • chai-semver - Semver plugin for Chai
  • chai-fs - Chai assertion plugin for the Node.js filesystem API. Uses path and synchronous fs to assert files and directories.
  • Chai Events - Make assertions about event emitters.
  • Chai HTTP - HTTP integration testing with Chai assertions.
  • chai-spy - 🔎 Spies for the Chai Assertion Library
  • Chai Assertions for RxJS Observables - ChaiRx extends Chai with a simple utility method emit for testing emits from an RxJS Observable stream using the Rx.TestScheduler.
  • chai-moment-string - chai plugin for validating a string with an expected moment format
  • chai-fireproof - Chai assertions and helpers for Firebase and Fireproof.
  • chai-eventemitter - This is a plugin for chai to simplify the testing of EventEmitter.
  • Chai Spies - It provides the most basic function spy ability and tests.
  • Sinon.JS Assertions for Chai - Sinon–Chai provides a set of custom assertions for using the Sinon.JS spy, stub, and mocking framework with the Chai assertion library. You get all the benefits of Chai with all the powerful tools of Sinon.JS.
  • chai-url - A chai assertion plugin for working with urls
  • chai-dom - chai-dom is an extension to the chai assertion library that provides a set of assertions when working with the DOM (specifically HTMLElement and NodeList)
  • In-Order Sinon-Chai Assertions - Sinon-Chai provides Chai assertions for Sinon.JS. Unfortunately, it does not deal with making sure a spy was called multiple time in a specific order.

Ejemplo

// Función
function sumar (p1, p2){
return p1 + p2;
}

// Test
mocha.setup('bdd');
const expect = chai.expect;
const should = chai.should();
describe("Test de la funcion sumar(p1, p2)", () => {

it('1 + 2 = 3', () => {
  expect(sumar( 1, 2)).to.equal(3);
});

it('\"2\" + 2 != \"4\"', () => {
  expect(sumar( "2", 2)).not.equal("4");
});

});

mocha.run();

Documentación

Sinon

IMG

Documentación

Ejemplo

// Función
function getTodos(listId, callback) {
    jQuery.ajax({
        url: '/todo/' + listId + '/items',
        success: function (data) {
            // Node-style CPS: callback(err, data)
            callback(null, data);
        }
    });
}

// Testing
after(function () {
    // When the test either fails or passes, restore the original
    // jQuery ajax function (Sinon.JS also provides tools to help
    // test frameworks automate clean-up like this)
    jQuery.ajax.restore();
});

it('makes a GET request for todo items', function () {
    sinon.replace(jQuery, 'ajax', sinon.fake());
    getTodos(42, sinon.fake());

    assert(jQuery.ajax.calledWithMatch({ url: '/todo/42/items' }));
});

Aprendiendo testing en JS y Node

IMG

Recursos