Unit Testing in JavaScript with Mocha, Chai and Karma SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Introduction to Unit Testing Svetlin Nakov Telerik Corporation
Advertisements

With Mocha and Karma Telerik Academy Telerik Software Academy.
JavaScript Basics Course Introduction SoftUni Team Technical Trainers Software University
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Composer packages Installing and Using Composer, Packagist, Packaging your code Mario Peshev Technical Trainer Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Unit Testing Building Rock-Solid Software SoftUni Team Technical Trainers Software University
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Project Tracking Tools Trello, Asana, Basecamp, GitHub Issue Tracker, TRAC Angel Georgiev Part-time Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
JavaScript Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Templating, Routing, lodash Extending functionality using Collections SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Web Fundamentals (HTML and CSS) Course Introduction SoftUni Team Technical Trainers Software University
Controls, Widgets, Grid…
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Web Development Tools Tools for Front-End Developers Writing HTML and CSS Code SoftUni Team Technical Trainers Software University
Web Fundamentals (HTML and CSS)
Responsive Design Design that Adapts to Different Devices SoftUni Team Technical Trainers Software University
Unit Testing Building Rock-Solid Software Svetlin Nakov Technical Trainer Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
Tables, Rows, Columns, Cells, Header, Footer, Colspan, Rowspan
CSS Transitions and Animations Animated HTML Elements SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
JavaScript Applications Course Introduction SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
JavaScript Tools Tools for Writing / Editing / Debugging JavaScript Code Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
JavaScript Applications Course Introduction SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Software Technologies Course Overview SoftUni Team Technical Trainers Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Team Work and Personal Skills Course Introduction Angel Georgiev Part-time Trainer Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
AngularJS Best Practices High Quality SPA Applications SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Auto Mapping Objects SoftUni Team Database Applications
Building Rock-Solid Software
Mocking tools for easier unit testing
Unit Testing with Mocha
Introduction to Unit Testing in JavaScript
Extending functionality using Collections
Introduction to TypeScript & Angular
Presentation transcript:

Unit Testing in JavaScript with Mocha, Chai and Karma SoftUni Team Technical Trainers Software University

 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 Table of Contents

What is Unit Testing?

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. Unit Test – Definition “Program testing can be used to show the presence of bugs, but never to show their absence!” Edsger Dijkstra, [1972]

5  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 Manual Testing

Unit Test – Example 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) throw new Error("1+2 != 3"); if (sum([1,2]) != 3) throw new Error("1+2 != 3"); if (sum([-2]) != -2) throw new Error("-2 != -2"); if (sum([-2]) != -2) throw new Error("-2 != -2"); if (sum([]) != 0) throw new Error("0 != 0"); if (sum([]) != 0) throw new Error("0 != 0");}

7  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 Unit Testing – Some Facts

8  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 Unit Testing – More Facts

9  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 Why Unit Tests?

Unit Testing in JavaScript

 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 Unit Testing in JavaScript

 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 QUnit

 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 Jasmine

 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 Mocha

Testing with Mocha 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 Mocha Overview

 To start working with Mocha follow the steps: 1. Get Mocha  Download mocha from GitHubGitHub  With bower  With NuGet 2. Setup a reporter  HTML reporter  Karma reporter Installing Mocha $ 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 Installing Mocha $ 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); }); });});

Running Tests with Mocha and Chai Live Demo

Mocha with Chai 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 Mocha with Chai expect = chai.expect; $ bower install chai

Mocha Reporters 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 Mocha Reporters

 The HTML reporter outputs in the browser  Needs an HTML template: Mocha HTML Reporter <head> </head><body> mocha.setup('bdd'); mocha.setup('bdd'); expect = chai.expect; expect = chai.expect; mocha.run(); mocha.run(); 1. Include the Mocha styles 2. Create report element with id mocha 3. Include mocha.js and chai.js 4. Setup Mocha 5. Import JS files 6. Run tests with Mocha

Mocha HTML Reporter Live Demo

Mocha Test Suites and Specs

 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  Test suites can be nested in one another Mocha Test Suites describe('#sum', function() { //here are the tests //here are the tests}); describe('Person', function() { describe('when initializing', … describe('when initializing', … describe('when changing name', … describe('when changing name', …});

 Specs (tests) are contained in a test suites  Call the function it(name, callback)  Has a name and a callback: Mocha Specs 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'); }); }); });

Mocha Test Suites and Tests Live Demo

Chai Assertions 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  Expect style  Should style Chai Assertions assert.equal(person.firstname(), 'Peter'); expect(person.firstname()).to.equal('Peter'); person.firstname().should.equal('Peter');

Chai Expect Assertion Style Using the BDD Styles

 Chai.js expect assertion style has a fluent and expressive syntax: Chai Expect Assertion Style 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);

Chai Assertions Live Demo

Karma 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 Overview

 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 Installing Karma $ 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: 3. Install one or many browser environments 4. Run and fill in the needed data 5. Start the Karma environment with Setting up Karma Environment $ npm install karma-mocha karma-chai --save-dev $ npm install karma-chrome-launcher --save-dev $ karma init $ npm install karma-phantomjs-launcher --save-dev $ karma start

Mocha in Karma Environment Live Demo

? ? ? ? ? ? ? ? ? Unit Testing in JavaScript

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 41  Attribution: this work may contain portions from  "JavaScript Applications" course by Telerik Academy under CC-BY-NC-SA licenseJavaScript ApplicationsCC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg