This document discusses testing single page web applications built with AngularJS. It covers using fixtures to stub HTTP responses during functional testing. Static fixtures can return pre-defined responses from files, while dynamic fixtures allow generating responses programmatically. The jasmine.test.SinonFakeServer wrapper facilitates advanced dynamic fixtures by intercepting AJAX requests and returning fake responses, simulating network delays. This allows testing the application without changing code to use stubbed responses during tests.
Powerpoint file(incl. animations!): http://db.tt/ktTDiQSG
Demostration module with example: http://db.tt/Ix2ovTno
This is the slides of the presentation "Drupal & Javascript" who presented at DrupalCamp Israel 2012.
Powerpoint file(incl. animations!): http://db.tt/ktTDiQSG
Demostration module with example: http://db.tt/Ix2ovTno
This is the slides of the presentation "Drupal & Javascript" who presented at DrupalCamp Israel 2012.
Overview of The Scala Based Lift Web FrameworkIndicThreads
All of us having experience with other web frameworks such as Struts,Tapestry, Rails, etc would ask “Why another framework? Does Lift really solve problems any differently or more effectively than the ones we’ve used before? The Lift Web Framework provides an advanced set of tools for quickly and easily building real-time, multi-users, interactive web applications. Lift has a unique advantage that no other web framework currently shares: the Scala programming language. Scala is a relatively new language developed by Martin Odersky and his group at EPFL Switzerland. Scala is a hybrid Object Oriented and Functional language that runs at native speeds on the JVM and fully interoperates with Java code. Lift is a hybrid web framework built on Scala. Lift derives its features and idioms from the best of existing web frameworks as well as the functional and OO features in Scala. It compiles to Java bytecode and runs on the JVM, which means that we can leverage the vast ecosystem of Java libraries just as we would with any other java web framework. This presentation details the advantages of this Scala based Web framework over all the existing frameworks that we have used uptil now and shows a small sample application built with Lift. We will create a basic application with a model that maps to RDBMS, web pages that correspond to back end logic and bind dynamically created content to elements on the webpage.
Stripes presentation for the Portuguese JUG session at JavaPT09 event.
Last version available at Speaker Deck: http://speakerdeck.com/samaxes/java-web-development-with-stripes.
Con la versione 7 di Drupal è stato introdotto il concetto di Entity, poi evoluto con la versione 8, utilizzato come base di buona parte degli elementi core (nodi, tassonomie, utenti, ...), ma - soprattutto - è stata data la possibilità di costruire entity custom. L'utilizzo di queste apre le possibilità di personalizzazione dello strumento ad un livello superiore velocizzando notevolmente lo sviluppo.
Verranno mostrate le potenzialità nell'uso delle Entity custom e le integrazioni possibili.
An idea of how to make JavaScript testable, presented at Stir Trek 2011. The world of JavaScript frameworks has changed greatly since then, but I still agree with the concepts.
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
HTML5 is the playing area, the strip, Javascript presentation frameworks are the fences and they are fierce and proud. In this presentation we will attend an interesting match between two of the emerging contenders in the MV* family: KnockoutJS and BackboneJS. We'll try to understand how they solve the same issues in modern web software development to better decide which one is suitable in our scenario.
Opencast Admin UI - Introduction to developing using AngularJSbuttyx
This presentation is intended to help developers anticipating using and potentially extending the new Admin UI get a hands-on introduction into the Angular JS portion of the software. It has been presented in the form of a workshop and therefore the last slides (starting with the 22) could seem a bit abstract.
This talk represents the combined experience from several web development teams who have been using Symfony2 since months already to create high profile production applications. The aim is to give the audience real world advice on how to best leverage Symfony2, the current rough spots and how to work around them. Aside from covering how to implement functionality in Symfony2, this talk will also cover topics such as how to best integrate 3rd party bundles and where to find them as well as how to deploy the code and integrate into the entire server setup.
This presentation covers some jQuery basics, as well as some general concepts you should understand about jQuery. You will find other tips and tricks sprinkled throughout before the live coding session starts.
The code from the live coding session is available here: https://github.com/dcneiner/jQuery-Bling and covers far more advanced topics than the slide portion of this presentation.
Is your web app drowning in a sea of JavaScript? Has your client-side codebase grown from "a snippet here and there" to "more JavaScript than HTML"? Do you find yourself writing one-off snippets instead of generalized components? You're not the only one. Learn about a handful of strategies you can use to keep your JavaScript codebase lean, modular, and flexible. We'll cover all the major pain points — MVC, templates, persisting state, namespacing, graceful error handling, client/server communication, and separation of concerns. And we'll cover how to do all this incrementally so that you don't have to redo everything from scratch.
Overview of The Scala Based Lift Web FrameworkIndicThreads
All of us having experience with other web frameworks such as Struts,Tapestry, Rails, etc would ask “Why another framework? Does Lift really solve problems any differently or more effectively than the ones we’ve used before? The Lift Web Framework provides an advanced set of tools for quickly and easily building real-time, multi-users, interactive web applications. Lift has a unique advantage that no other web framework currently shares: the Scala programming language. Scala is a relatively new language developed by Martin Odersky and his group at EPFL Switzerland. Scala is a hybrid Object Oriented and Functional language that runs at native speeds on the JVM and fully interoperates with Java code. Lift is a hybrid web framework built on Scala. Lift derives its features and idioms from the best of existing web frameworks as well as the functional and OO features in Scala. It compiles to Java bytecode and runs on the JVM, which means that we can leverage the vast ecosystem of Java libraries just as we would with any other java web framework. This presentation details the advantages of this Scala based Web framework over all the existing frameworks that we have used uptil now and shows a small sample application built with Lift. We will create a basic application with a model that maps to RDBMS, web pages that correspond to back end logic and bind dynamically created content to elements on the webpage.
Stripes presentation for the Portuguese JUG session at JavaPT09 event.
Last version available at Speaker Deck: http://speakerdeck.com/samaxes/java-web-development-with-stripes.
Con la versione 7 di Drupal è stato introdotto il concetto di Entity, poi evoluto con la versione 8, utilizzato come base di buona parte degli elementi core (nodi, tassonomie, utenti, ...), ma - soprattutto - è stata data la possibilità di costruire entity custom. L'utilizzo di queste apre le possibilità di personalizzazione dello strumento ad un livello superiore velocizzando notevolmente lo sviluppo.
Verranno mostrate le potenzialità nell'uso delle Entity custom e le integrazioni possibili.
An idea of how to make JavaScript testable, presented at Stir Trek 2011. The world of JavaScript frameworks has changed greatly since then, but I still agree with the concepts.
MV* presentation frameworks in Javascript: en garde, pret, allez!Roberto Messora
HTML5 is the playing area, the strip, Javascript presentation frameworks are the fences and they are fierce and proud. In this presentation we will attend an interesting match between two of the emerging contenders in the MV* family: KnockoutJS and BackboneJS. We'll try to understand how they solve the same issues in modern web software development to better decide which one is suitable in our scenario.
Opencast Admin UI - Introduction to developing using AngularJSbuttyx
This presentation is intended to help developers anticipating using and potentially extending the new Admin UI get a hands-on introduction into the Angular JS portion of the software. It has been presented in the form of a workshop and therefore the last slides (starting with the 22) could seem a bit abstract.
This talk represents the combined experience from several web development teams who have been using Symfony2 since months already to create high profile production applications. The aim is to give the audience real world advice on how to best leverage Symfony2, the current rough spots and how to work around them. Aside from covering how to implement functionality in Symfony2, this talk will also cover topics such as how to best integrate 3rd party bundles and where to find them as well as how to deploy the code and integrate into the entire server setup.
This presentation covers some jQuery basics, as well as some general concepts you should understand about jQuery. You will find other tips and tricks sprinkled throughout before the live coding session starts.
The code from the live coding session is available here: https://github.com/dcneiner/jQuery-Bling and covers far more advanced topics than the slide portion of this presentation.
Is your web app drowning in a sea of JavaScript? Has your client-side codebase grown from "a snippet here and there" to "more JavaScript than HTML"? Do you find yourself writing one-off snippets instead of generalized components? You're not the only one. Learn about a handful of strategies you can use to keep your JavaScript codebase lean, modular, and flexible. We'll cover all the major pain points — MVC, templates, persisting state, namespacing, graceful error handling, client/server communication, and separation of concerns. And we'll cover how to do all this incrementally so that you don't have to redo everything from scratch.
Mobile applications Development - Lecture 12
Javascript
jQuery (Zepto)
useful microframeworks
This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).
http://www.di.univaq.it/malavolta
Javascript and first-class citizenry: require.js & node.js
Javascript on web pages is ubiquitous and its problems are legendary. Javascript, seen as a second-class code citizen, is usually hacked together even by seasoned developers. New libraries (jQuery, prototype, backbone, knockout, underscore) and runtime tools (firebug, jasmine) look like they solve many problems - and they do. But they still leave poorly written code as just that. One key problem is that all javascript code lives globally and this results in poorly managed, tested and delivered code.
In this session, I will illustrate that we can treat javascript as a first-class citizen using with require.js and node.js: it can be modular, encapsulated and easily unit tested and added to continuous integration cycle. The dependencies between javascript modules can also be managed and packaged just like in C# and Java. In the end, we can resolve many javascript difficulties at compile time rather than waiting until runtime.
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
Using Backbone.js to move state to the client-side and the benefits of using a JavaScript MVC framework.
Delivered at SuperMondays, Newcastle upon Tyne, on 26th September 2011.
When you move beyond adding simple enhancements to your website with jQuery and start building full-blown client-side applications, how do you organize your code? At this month's Triangle JS Meetup, we'll take a look at patterns for application development using jQuery that promote the principles of tight encapsulation and loose coupling, including classes, the publish/subscribe paradigm, and dependency management and build systems.
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
09 - Express Nodes on the right Angle - Vitaliy Basyuk - IT Event 2013 (5)
60 вузлів під правильним кутом - миттєва розробка програмних додатків використовуючи Node.js + Express + MongoDB + AngularJS.
Коли ми беремось за новий продукт, передусім ми думаємо про пристрасть, яка необхідна йому, щоб зробити користувача задоволеним і відданим нашому баченню. А що допомагає нам здобути прихильність користувачів? Очевидно, що окрім самої ідеї, також важлими будуть: зручний користувацький інтерфейс, взаємодія в реальному часі та прозора робота з даними. Ці три властивості ми можемо здобути використовучи ті чи інші засоби, проте, коли все лиш починається, набагато зручніше, якщо інструменти допомагають втілити бажане, а не відволікають від головної мети.
Ми розглянемо процес розробки, використовуючи Node.js, Express, MongoDB та AngularJS як найбільш корисного поєднання для отримання вагомої переваги вже на старті вашого продукту.
Віталій Басюк
http://itevent.if.ua/lecture/express-nodes-right-angle-rapid-application-development-using-nodejs-express-mongodb-angular
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
2. Agenda
ns:
eb applicatio MVC framewor
Single page w ks:
s AngularJS
basic concept
Javascript maturity
Testing: n it
n onJS, FuncU
Jasmine, Si
A simple dem
o
app: Jashboa
rd
4. Runs in the browser Breaks in the browser
The language of choice The only choice ?
Simple to test (manually) Test automation ?
Lightweight and expressive Multiparadigm
Dynamic How do I know I made a mistake?
5. The Challenges
o UI interactions
o Asynchronous communication
o Frequent DOM manipulation
How to separate view and How to test effectively
behaviour Event handling
Where’s the business logic? Data-binding
Where’s the rendering logic? Callbacks
9. Two-way data binding
Declarative
Binding
<input type="text" name="dashboardName” data-ng-model="dashboard.name”>
...
<div>{{dashboard.name}}</div>
Automatic
view refresh
(Data) View
View
Model Model
10. DOM decoupling and behaviour
view separation
Example: we want to display a
message box in alert style
11. Create a dom element to
represent the alert message
...
<div class="alert_msg modal hide">
<div class="modal-header">
</div>
<div class="modal-body">
</div>
</div>
...
!
$(".alert_msg .modal-header").html('<div>Remove monitor ...</div>');!
$(".alert_msg .modal-body").html('<div>If you delete...</div>');!
$(".alert_msg").modal('show');!
!
Change the DOM
Display the message
12. <div class="alert_msg modal hide">
data-jb-alert-box class="alert_msg modal hide">
<div class="modal-header"> Introduce
<div>{{title}}</div> templates
</div>
<div class="modal-body">
<div>{{message}}</div>
</div>
</div>
Register the
alertBoxDirective: function(alertService){! element to be
Wrap the
return function(scope, element) {!
widget logic used by the
alertService.bindTo(element);!
};! into a service alert service
}!
alertService.showAlert=function(options){!
Invoke the service passing
scope.title = options.title;!
the message data scope.message = options.message;!
$(element).modal('show');!
$(".alert_msg").modal('show');!
alertService.showAlert({! };!
title: "Remove monitor...",!
message: "If you delete..."!
});!
13. DOM decoupling and behaviour
view separation (2)
Example: we want to display an
overlay message while the data
loads from the server
14. MainController: function(scope, repository) {!
...!
show the overlay when
var loadData = function() {! loading starts
$.blockUI({message: $("overlay-msg").html().trim()})!
repository.loadDashboards({!
repository.loadDashboards({!
success: function(data) {!
! success: function(data) {!
!_.each(data, function(d){scope.dashboards.push(d);});!
! });!_.each(data, function(d){scope.dashboards.push(d);}); ! !!
!
};! });!
! $.unblockUI();!
! };! });! hide the overlay when
! };! loading completes
Create a dom element to
represent the overlay message
<div class="hide">
<div class="overlay-msg">
<spam class="ajax-loader-msg"> Loading dashboards... Please wait.</spam>
</div>
</div>
15. MainController: function(scope, repository) overlayService) {!
repository, {!
...!
var loadData = function() {!
overlayService.show("overlay-msg");!
$.blockUI({message: $("overlay-msg").html().trim()})! service
Inject the
repository.loadDashboards({!
into the controller
success: function(data) {!
! !_.each(data, function(d){scope.dashboards.push(d);});! !
function(d){scope.dashboards.push(d);}); !
! !overlayService.hide();!
!$.unblockUI();!
});!
};!
OverlayService: function() {!
var blockUISettings = { ... };! Extract the widget logic
! into a service
this.show = function(selector) {!
blockUISettings.message = $(selector).html().trim();!
$.blockUI(blockUISettings);!
};!
this.hide = function() {!
$.unblockUI();!
};!
}!
17. DOM decoupling and behaviour
view separation (3)
Other custom directive examples:
<div data-jb-draggable>...</div> make an element draggable
<div data-jb-resizable>...</div> make an element resizable
<div data-jb-tooltip>...</div> set an element tooltip
<div data-jb-dialog>...</div> open an element in a dialog
<div data-jb-form-validation>...</div> trigger input validation rules
18. Dependency injection
DashboardFormController: function(scope, repository) {!
scope.saveDashboard = function() {!
repository.createDashboard({name: this.dashboardName});!
...!
!
Repository: function(httpService) {!
this.createDashboard = function(parameters) {!
!httpService.postJSON("/ajax/dashboard", parameters);!
};!
...!
!
DashboardFormController Repository HttpService
With Angular you can use plain javascript to define your models,
services, controllers, etc.
19. Good practices with
o Use multiple controllers to separate the
responsibilities in the different sections of your page
o Wrap your external libraries into services to provide
decoupling from 3rd party plugins
o Use custom directives to define reusable components
o The primary function of the Angular Scope is to be
the execution context (model) for your views/
templates. Be mindful when leveraging scope
inheritance and scope data sharing.
o Use events as means to communicate
o Isolate your objects/functions so that they can be
easily tested
23. Loading dependencies:
<script type='text/javascript' ! One line in your HTML to
src='steal/steal.js?jashboard/loader.js'>! dynamically load all
</script>! your dependencies
steal(!
{ src: "css/bootstrap.min.css", packaged: false },!
...!
).then(!
{ src: 'lib/angular.min.js', packaged: false },!
{ src: 'lib/underscore-min.js', packaged: false },!
{ src: 'lib/bootstrap.min.js', packaged: false },!
...!
).then(function() {!
steal('steal/less')!
.then("css/jashboard.less")!
.then("jashboard/modules.js")!
});!
loader.js
24. Unit testing
Behaviour driven development in Javascript
http://pivotal.github.com/jasmine/
Advanced spying, mocking and stubbing
http://sinonjs.org/
26. Unit testing callbacks
synchronous call asynchronous callback
var Controller = function(scope, http) {!
...!
this.loadData = function(){!
http.getJSON("/ajax/dashboards").done(function(data) {!
scope.dashboards = data;!
});!
};!
Set espectations on
var scope = {}, http = {};!
the synchronous call
http.getJSON = sinon.stub();! Stub the
! promise object
http.getJSON.withArgs("/ajax/dashboards").returns({!
done: function(callback) { callback("test-data"); }!
}));!
!
new Controller(scope, http).loadData();!
! verify
expect(scope.dashboards).toEqual("test-data");! asynchronous call
!
27. Warning!
var scope = {}, http = {};!
http.getJSON = jasmine.createSpy().andReturn({!
done: function(callback) { callback("test-data"); }!
}));!
!
new Controller(scope, http).loadData();!
!
expect(http.getJSON).toHaveBeenCalledWith("/ajax/dashboards");!
expect(scope.dashboards).toEqual("test-data");!
!
Mocking and stubbing Highly behaviour focused tests
dependencies
No guaranteed objects wiring
• What if method getJSON is
Javascript is a
renamed?
dynamic language • What if the return value changes
interface?
35. Browser/client
side
Asynchronous
HTTP request
(AJAX)
Stub HTTP response
We want the browser to use our stubbed
ajax responses only during our tests,
without having to change our code
36. file://.../index.html?test_scenario=sample_scenario
...!
steal ({src: 'test/funcunit/test_scenario_loader.js', ignore: true});!
!
(function() {!
var regexp = /?test_scenario=(w+)/!
var match = regexp.exec(window.location.search);!
if (match) {!
var scenarioName = match[1];!
steal(!
{ src: 'lib/sinon-1.5.2.js', ignore: true },!
{ src: 'jquery/dom/fixture', ignore: true }!
).then("test/funcunit/scenarios/" + scenarioName + ".js");!
}!
}());!
test_scenario_loader.js
39. works by overriding jQuery.ajaxTransport, basically intercepting
the jQuery.ajax() request and returning a fake response
Great for static fixtures
It only works with jQuery
Limited support for templated Urls
Simulating a delayed response affects all the responses
40. Advanced dynamic fixtures with
Wrapper around
sinon.fakeServer and
sinon.useFakeXMLHttpRequest
var server = new jashboard.test.SinonFakeServer();!
!
server.fakeResponse = function(httpMethod, url, response);!
response = {!
returnCode: 200,!
contentType: "application/json",!
content: {},!
delay: 1!
}!
41. Simulating response delays
server.fakeResponse("GET", "/ajax/monitor/monitor_1/runtime", {!
content: {!
last_build_time: "23-08-2012 14:32:23",!
duration: 752,!
success: true,!
status: 1!
},! we can set individual response
delay: 3! delay time for each response
});!
!
server.fakeResponse("GET", "/ajax/monitor/monitor_2/runtime", {!
content: {!
last_build_time: "25-08-2012 15:56:45",!
duration: 126,!
success: false,!
status: 0!
},!
delay: 1!
});!
42. Using Url templates
server.fakeResponse("POST", //ajax/dashboard/(w+)/monitor/, !
function(request, dashboard_id) {!
!...!
});!
!
server.fakeResponse("PUT", //ajax/monitor/(w+)/position/, !
function(request, monitor_id) {!
var position = JSON.parse(request.requestBody);!
console.log(monitor_id + " moved to [" + position.top + ”, " +
position.left + "]");!
return {returnCode: 201};!
});!
43. Simulate scenarios not only for
testing
Spike and prototype new features
Explore edge cases
Verify performance
44. Automating functional tests
o Extension of QUnit
o Integrated with popular automation frameworks like
Selenium and PhantomJS (?)
• Open a web page
• Use a jQuery-like syntax to look up elements and simulate
a user action
• Wait for a condition to be true
• Run assertions
45. Examples of functional tests
module("Feature: display monitors in a dashboard", {!
setup: function() {!
S.open('index.html');!
}!
});!
test("should load and display build monitor data", function() {!
S("#tab-dashboard_2").visible().click();!
S("#monitor_2 .monitor-title").visible().text("Epic build");!
...!
)}!
!
module("Feature: create a new dashboard", {!
...!
test("should create a new dashboard", function() {!
//open form dialog!
...!
S("input[name='dashboardName']).visible().type("some name");!
S("#saveDashboard").visible().click();!
S(".dashboard-tab").size(4, function() {!
equal(S(".dashboard-tab").last().text(), "some name"); !
});!
});!
46. Testing our scenarios/fixtures
module("Feature: display monitors in a dashboard", {!
setup: function() {!
S.open('index.html?test_scenario=display_dashboards_data');!
S.open('index.html');!
}!
});!
test("should load and display build monitor data", function() {!
S("#tab-dashboard_2").visible().click();!
featureHelper.verifyElementContent("#monitor_2",!
{!
'.monitor-title': "Epic build",!
'.build-time': "28-08-2012 11:25:10",!
'.build-duration': "09:56",!
'.build-result': "failure",!
'.build-status': "building"!
}!
);!
featureHelper.verifyElementContent("#monitor_3",!
{!
'.monitor-title': "Random text",!
'pre': "some very random generated text ..."!
}!
);!
});!
47. Verifying expected ajax requests
test("should create a new dashboard", function() {!
openDashboardDialog();!
featureHelper.inputText("input[name='dashboardName']", "TEST");!
S("#saveDashboard").visible().click();!
...!
funcunit test
$.fixture("POST /ajax/dashboard", function(ajaxOriginalOptions, !
ajaxOptions, headers) {!
var data = JSON.parse(ajaxOptions.data);!
!
if("TEST" === data.name) {!
return [201, "success", {json: {id: "dashboard_4", name: "TEST", !
monitors: [] } }, {} ];!
}!
throw "unexpected data in the POST request: " + ajaxOptions.data;!
});!
test scenario
48. Fast functional tests
We can open the browser and run unit tests directly from the file system
+ test scenarios + response fixtures
49. SUMMARY
Modern Javascript single page Web applications can be complex
The risk introduced by such complexity should be addressed
by adopting proper practices, such as
o leveraging frameworks that can simplify the development
o keeping a neat and organised project code structure
o applying rules of simple design to create readable and
maintainable codebase
o using mocks / stubs to create concise unit tests
o running fast functional regression tests to increase
confidence in refactoring
Libraries like $.fixture and Sinon.JS can be helpful for rapid
spiking/prototyping and testing of front-end features