With Mocha and Karma Telerik Academy Telerik Software Academy.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Coding JavaScript the expressive way Learning & Development Telerik Software Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
C# Fundamentals – Part I
Welcome to the JSON-stores world Telerik Software Academy Databases.
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Past, Present and Future Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Course Introduction Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy End-to-end JavaScript Applications.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Course Overview Doncho Minkov Telerik Software Academy Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Unit Testing in JavaScript with Mocha, Chai and Karma SoftUni Team Technical Trainers Software University
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Introduction to Unit Testing in JavaScript
Presentation transcript:

With Mocha and Karma Telerik Academy Telerik Software Academy

 Unit Testing  Overview  Test-driven & behavior-driven development  Mocha & Chai  Overview and installation  Running simple tests  Mocha HTML Reporter and Karma  Creating a test suites and specs

A unit test is a piece of code written by a developer that exercises a very small, specific area of functionality of the code being tested. “Program testing can be used to show the presence of bugs, but never to show their absence!” Edsger Dijkstra, [1972]

 You have already done unit testing  Manually, by hand  Manual tests are less efficient  Not structured  Not repeatable  Not on all your code  Not easy to do as it should be 5

function sum(numbers) { var sum = 0; var sum = 0; for (var i=0; i<numbers.length; i++) for (var i=0; i<numbers.length; i++) sum += array[i]; sum += array[i]; return sum; return sum;} void testSum() { if (sum([1,2]) != 3) if (sum([1,2]) != 3) throw new Error("1+2 != 3"); throw new Error("1+2 != 3"); if (sum([-2]) != -2) if (sum([-2]) != -2) throw new Error("-2 != -2"); throw new Error("-2 != -2"); if (sum([]) != 0) if (sum([]) != 0) throw new Error("0 != 0"); throw new Error("0 != 0");}

 Tests are specific pieces of code  In most cases unit tests are written by developers, not by QA engineers  Unit tests are released into the code repository (TFS / SVN / Git) along with the code they test  Unit testing framework is needed  QUnit, Jasmine, Mocha 7

 All objects should be tested  All methods should be tested  Trivial code may be omitted  E.g. property getters and setters  Private methods can be omitted  Some gurus recommend to never test private methods  this can be debatable  Ideally all unit tests should pass before check- in into the source control repository 8

 Unit tests dramatically decrease the number of defects in the code  Unit tests improve design  Unit tests are good documentation  Unit tests reduce the cost of change  Unit tests allow refactoring  Unit tests decrease the defect-injection rate due to refactoring / changes 9

 There are too many frameworks for unit testing for JavaScript  Some use TDD  Others use BDD  Some of the frameworks:  TDD  QUnit, JsUnit & Mocha  BDD  Jasmine & Mocha

 QUnit was developed to test jQuery  Developed by John Resig  QUnit has the following features:  Uses test-driven development (TDD)  Has a lot of asserts to match every need  Can test async code

 Jasmine is an open-source testing framework  Can run in both the browser and on Node.js  Uses behavior-driven development  Widely used  Introduces in 2008  Jasmine has the following features:  Easy-to-read (expressional) syntax  Testing async code  Spies (mocking objects and methods)  DOM testing

 Mocha is the new kid on the block  Open source framework, introduces in 2012  Can run in both the browser and on Node.js  Plugins for test syntax, spies, etc…  Mocha has the following features:  Easy-to-read (expressional) syntax  Testing async code  Supports both BDD and TDD  The most used plugin for syntax is Chai.js  The most used plugin for spies is Sinon

Overview and Installation

 Mocha is a feature-rich framework for testing JavaScript  Run in both the browser and on Node.js  Can test async code  Compatible with Karma & other test runners  Pluggable  Different plugins to add even more features

 To start working with Mocha follow the steps: 1.Get Mocha  Download mocha from GitHub GitHub  With bower  With NuGet 2.Setup a reporter  HTML reporter  Karma reporter $ bower intall mocha PM> Install-Package MochaChaiBdd

 To start working with Mocha follow the steps: 3.Select a plugin for the test syntax  Mostly used is chai.js 4.Start writing tests $ bower intall chai describe('#sum', function () { it('when empty array, expect to return 0', function () { it('when empty array, expect to return 0', function () { var actual = sum([]); var actual = sum([]); expect(actual).to.equal(0); expect(actual).to.equal(0); }); }); it('when with single number, expect the number', function () { it('when with single number, expect the number', function () { var number = 6; var number = 6; var actual = sum([number]); var actual = sum([number]); var expected = number; var expected = number; expect(actual).to.equal(expected); expect(actual).to.equal(expected); }); });});

Live Demo

Where Mocha can report the result of the tests?

 What is a reporter?  Reporter is the place where Mocha outputs the result from the unit tests  If the tests passed  Or if they failed  Mocha has a lot of reporters:   Good reporters are the HTML reporter, the Spec reporter and the Karma reporter

 The HTML reporter outputs in the browser  Needs an HTML template: <head> </head><body> mocha.setup('bdd'); mocha.setup('bdd'); expect = chai.expect; expect = chai.expect; mocha.run(); mocha.run();

 The HTML reporter outputs in the browser  Needs an HTML template: <head> </head><body> mocha.setup('bdd'); mocha.setup('bdd'); expect = chai.expect; expect = chai.expect; mocha.run(); mocha.run(); Include the Mocha styles

 The HTML reporter outputs in the browser  Needs an HTML template: <head> </head><body> mocha.setup('bdd'); mocha.setup('bdd'); expect = chai.expect; expect = chai.expect; mocha.run(); mocha.run(); Mocha will report here

 The HTML reporter outputs in the browser  Needs an HTML template: <head> </head><body> mocha.setup('bdd'); mocha.setup('bdd'); expect = chai.expect; expect = chai.expect; mocha.run(); mocha.run(); Setup Mocha

 The HTML reporter outputs in the browser  Needs an HTML template: <head> </head><body> mocha.setup('bdd'); mocha.setup('bdd'); expect = chai.expect; expect = chai.expect; mocha.run(); mocha.run(); Run the tests with Mocha

Live Demo

Overview

 Karma is a testing environment  Getting instant feedback  Can run in any browser environment  Even in phantom.js environment  Karma can work with most of the testing frameworks  Mocha  Jasmine  QUnit

 Karma is a Node.js package  Must have Node.js installed, to run Karma  Install Node.js from  There is an installer for every platform:  Windows  Linux  Macintosh  Install Karma with $ npm install karma -g

 To setup karma environment for a project follow the steps: 1.Install karma, if you have not done so already 2.Install the necessary packages for the wanted test framework: $ npm install karma-mocha karma-chai --save-dev 3.Install one or many browser environments $ npm install karma-chrome-launcher --save-dev 4.Run and fill in the needed data 5.Start the Karma environment with $ karma init $ npm install karma-phantomjs-launcher --save-dev $ karma start

Live Demo

Adding assertion framework

 Mocha is made pluggable  Can use almost any assertion framework  The most used is Chai.js  Chai.js uses behavior-driven development  To use Chai in Mocha, do the following:  Install Chai:  Add chai.js to your reporter  Set the global expect object to chai.expect expect = chai.expect; $ bower install chai

 Mocha uses test suites to order the tests  Tests suites are created with the describe(name, callback) function  Provide a name of the test suite and a callback function describe('#sum', function() { //here are the tests //here are the tests});  Test suites can be nested in one another describe('Person', function() { describe('when initializing', … describe('when initializing', … describe('when changing name', … describe('when changing name', …});

 Spects (tests) are contained in a test suites  Call the function it(name, callback)  Has a name and a callback: describe('Person', function() { describe('when initializing', function(){ describe('when initializing', function(){ it('with valid names, expect ok', function(){ it('with valid names, expect ok', function(){ var person = new Person('Peter', 'Petrov'); var person = new Person('Peter', 'Petrov'); expect(person.firstname()).to.equal('Peter'); expect(person.firstname()).to.equal('Peter'); expect(person.lastname()).to.equal('Petrov'); expect(person.lastname()).to.equal('Petrov'); }); }); });

Live Demo

How to use Chai.js?

 Chai.js is a assertion framework  Allows to assert expected/actual in tests  Chai.js has three assertion styles  Assert style assert.equal(person.firstname(), 'Peter');  Expect style expect(person.firstname()).to.equal('Peter');  Should style person.firstname().should.equal('Peter');

Using the BDD Styles

 Chai.js expect assertion style has a fluent and expressive syntax: expect(person.firstname()).to.equal('Peter');expect(person).to.be.a('Person');expect(person).to.not.be.undefined;expect(person).not.to.be.null;expect(person).to.be.ok;expect(person).not.to.be.ok;expect(function(){ //without name //without name new Person(); new Person();}).to.throw(ReferenceError);

Live Demo

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране