JS, Node.js, Frontend, Backend, Firebase, Express, Patrones, HTML5_APIs, Asincronía, Websockets, Testing
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();
const controlador = false;
console.assert(controlador, "\"controlador\" es igual a \"false\"");
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 } }
- Strict mode
assert(value[, message])
assert.deepEqual(actual, expected[, message])
assert.deepStrictEqual(actual, expected[, message])
assert.deepStrictEqual
: Comparison detailsassert.doesNotReject(block[, error][, message])
assert.doesNotThrow(block[, error][, message])
assert.equal(actual, expected[, message])
assert.fail([message])
assert.ifError(value)
assert.notDeepEqual(actual, expected[, message])
assert.notDeepStrictEqual(actual, expected[, message])
assert.notEqual(actual, expected[, message])
assert.notStrictEqual(actual, expected[, message])
assert.ok(value[, message])
assert.rejects(block[, error][, message])
assert.strictEqual(actual, expected[, message])
assert.throws(block[, error][, message])
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
- CucumberJS - Cucumber for JavaScript
- Unexpected - The extensible BDD assertion toolkit
- 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
- 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
- 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
- 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
- OWASP Glue - Application Security Automation
- OWASP ZAP - The OWASP ZAP core project
- BeEF - Manipulate the browser exploiting any XSS vulns you find
- 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.
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
- Web Oficial
- Documentación
- Introduction to Unit Testing
- QUnit en Github
- El equipo
- @qunitjs en Twitter
- QUnit Forum
- QUnit Cookbook
QUnit.module( name [, hooks] [, nested ] )
QUnit.only( name, callback )
QUnit.skip( name )
QUnit.start()
QUnit.test( name, callback )
QUnit.todo( name, callback )
async( [ acceptCallCount = 1 ] )
deepEqual( actual, expected [, message ] )
equal( actual, expected [, message ] )
expect( amount )
notDeepEqual( actual, expected [, message ] )
notEqual( actual, expected [, message ] )
notOk( state [, message ] )
notPropEqual( actual, expected [, message ] )
notStrictEqual( actual, expected [, message ] )
ok( state [, message ] )
propEqual( actual, expected [, message ] )
pushResult( data: { result, actual, expected, message } )
rejects( promise[, expectedMatcher][, message ] )
step( [ message ] )
strictEqual( actual, expected [, message ] )
throws( blockFn[, expectedMatcher][, message ] )
timeout( duration )
verifySteps( steps [, message ] )
QUnit.assert
QUnit.config
QUnit.dump.parse( data )
QUnit.extend( target, mixin )
QUnit.push( result, actual, expected, message )
QUnit.stack( [ offset = 0 ] )
QUnit.begin( callback )
QUnit.done( callback )
QUnit.log( callback )
QUnit.moduleDone( callback )
QUnit.moduleStart( callback )
QUnit.on( eventName, callback )
QUnit.testDone( callback )
QUnit.testStart( callback )
Las claves
- Mocha es el framework de testing isomórfico
- Chai es la librería de aserciones que ofrece tres interfaces (assert, expect y shpuld)
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 synchronousfs
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 theRx.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
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' }));
});
Recursos
- A guide to unit testing in JavaScript
- How Netflix does A/B Testing
- An Overview of JavaScript Testing in 2018
- I Spent $30,000 Testing Different Blog Designs — Here’s What I Found
- An Overview of JavaScript Testing in 2017
- Airbnb Guerilla Usability Testing
- A crash course on testing with Node.js
- The easy way to start automatically testing your website
- Why End-to-End Testing is Important for Your Team
- JS Vanilla Test Code Coverage
- Vanilla JS Testing — Part II
- AVA, low-config testing for JavaScript
- Revisiting Node.js Testing: Part 1
- How to test JavaScript with Mocha — The Basics
- Node.js End-to-End Testing with Nightwatch.js
- How to automate tests and deployments of Node.js apps
- Github | TheJambo/awesome-testing
- Github | atinfo/awesome-test-automation
- Github | ligurio/awesome-software-quality
- 7 Things Awesome Testers do That Don't Look Like Testing
- 5 Awesome Mobile Application Testing Tools & Platforms for Testers
- Software Testing for Continuous Delivery
- API Unit Testing with Node JS
- Node Hero - Node.js Unit Testing Tutorial
- Unit Testing and TDD in Node.js – Part 1
- JavaScript — Unit Testing using Mocha and Chai
- Lo mejor y peor de Mocha y de los unit tests en JavaScript
- How to mock a dependency in a Node.js, and why you should do it.
- How to mock requests for unit testing in Node
- Using Jasmine to Test Node.js Applications
- How to correctly unit test Express server
- Node.js Unit Testing Tutorial with Jasmine
- Testing Node.js with Mocha and Chai
- Getting Started with Node.js and Mocha
- Github | unicodeveloper/awesome-tdd
- 8 Reasons Why Unit Tests are Awesome
- The No. 1 unit testing best practice: Stop doing it
- Unit Tests, How to Write Testable Code and Why it Matters
- nodeJS-testing con jasmine
- HolaMundo con Jasmine
- Unit testing using mocha and chai
- NodeJS testing mocha chai
1 - Vamos a jugar haciendo un poco de testing en Node.