Welcome!

Java IoT Authors: Automic Blog, Liz McMillan, Elizabeth White, Pat Romanski, Roger Strukhoff

Related Topics: @DevOpsSummit, Java IoT, Cloud Security

@DevOpsSummit: Blog Post

Unit Testing By @Logentries | @DevOpsSummit [#DevOps]

Unit testing is very important for both the quality of the code and the well being of the developer

Unit Testing with Karam & Jasmine for AngularJS

by Philip Quinn of Logentries

So you've started to build applications with AngularJS; or, maybe you've done unit testing before but haven't used it with AngularJS; or, maybe it's all new to you, but either way this article should help to orient you to the value of using Karma with Jasmine and offer some tips on displaying functionalities of Angular JS. Let's get started!

My app is small it doesn't need any tests, right?

unit-testing-with-karma-jasmine-for-angularjs-2

Wrong!

A small app can have errors and it's bad practice to have an untested app.

Besides, a small app is the perfect place to get started in using proper unit testing because there won't be many tests and the functionality will be less complex.

First of all, what is Unit Testing?
Unit testing is very important for both the quality of the code and the well being of the developer. It allows for them to freely change their code and not just hope that it's not a breaking change, as the test will recognize the break straight away. This will minimize the number of regressions in the code.

Unit tests are all about splitting your code into small testable modules with each module having its own functionality and level of abstraction. This is where AngularJS shines.

An added bonus is that the unit tests will act as a type of documentation because it describes the expected behavior of the functions and modules. Unit tests don't care how your code does the task, it just cares about the results.

Okay, but when should I write unit tests?
Short answer - the start of the project is the ideal time. You will have all your tests and then can work toward writing your code with passing them in mind.

Sadly it is unrealistic to expect complete coverage with unit testing, so my suggestion is write as many as you can possibly think of at the start, and if new components appear, then they should be tested too; a more iterative process of revisiting tests should be used.

What testing framework should I use?
AngularJS can be tested in a lot of ways, by lots of testing frameworks, including but certainly not limited to mocha, jasmine, qunit, and sin on.

There are a lot of choices, but here's the secret: your choice really doesn't matter because there is no "best" option; they are all very similar.

If you are torn and love brilliant documentation (who doesn't) I would choose Jasmine (used proudly by the Logentries team btw).

After you pick your testing framework, you can now choose a task runner. The most well known include Karma and Protractor (both by the Angular team). For our examples we will be using Karma.

Now that you know some basics on why you should be using unit test, and you have an Angular project ready, lets get our hands on an example.

We'll need to install some dependencies for running unit tests with Karma and Jasmine.
To do this, you should run the following lines on the command line:

npm install karma --save-dev
npm install karma-phantomjs-launcher --save-dev
npm install karma-jasmine --save-dev

Now configure your karma.conf.js file using this guide.

How to design a test?

Scenario

  • "A calculator that adds and subtracts"

This scenario can be broken into features, which will in turn be broken into units of testable code.

The calculator has two main features, adding and subtracting numbers. These features can be split into units, such as the methods for addition and subtraction. These methods need to be tested and there may be many different cases that need to be taken into account. A possible example is below, but you may come up with some more tests.

describe('Calculator ', function() {

// necessary
it('should add two numbers correctly', function() {});
it('should subtract two numbers correctly', function() {});

// helpful but not needed
it('should add negative numbers', function() { });
it('should reject non numbers', function() { });
});

The "describe()" method defines our test suite. This takes a string with the convention that it describes the module which is being tested.

An "it()" is a proper test spec. Put what you want to be tested here, the convention is that it should read as a sentence, e.g. ‘it is expected to do this' reads as "it is expected to do this"

How do I use it with my AngularJS app?
Here is an example of a very basic controller. It only has a scope variable and we will test if this value is correct.

 var myApp = angular.module('myApp',[]);
myApp.controller('HelloWorldController', 
  ['$scope', function($scope) {
$scope.greeting = 'Hello World!';
}]);

Jasmine Test

describe(‘Hello World example ', function() {

beforeEach(module(‘app');

var HelloWorldController,
scope;

beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
HelloWorldController = $controller('MainCtrl', {
$scope: scope
});
}));
it('says hello world!', function () {
expect(scope.greeting).toEqual("Hello world!");
});

});

Run your test with:

karma start karma.conf.js

Every "beforeEach()" function is executed right before the tests are conducted. In the above case the function gets access to your angular module and then injects the controller and scope, so that it can be tested. This allows you to set up for each assertion, allowing the same clean set up for all your tests.

Some of the possible expectations include:

  • toEqual, toBe, toBeTruthy, toBeFalsy
  • toBe for negation

Jasmine has you covered if you want to ignore some of the tests temporarily. "xdescribe" will ignore a "describe" and "xit" will ignore a specific test.

Conclusion
So now you can run a basic unit test for your AngularJS app and slowly begin to build out to more complex tests. Once you've got your unit tests in place you have the foundations for a great application!

More Stories By Trevor Parsons

Trevor Parsons is Chief Scientist and Co-founder of Logentries. Trevor has over 10 years experience in enterprise software and, in particular, has specialized in developing enterprise monitoring and performance tools for distributed systems. He is also a research fellow at the Performance Engineering Lab Research Group and was formerly a Scientist at the IBM Center for Advanced Studies. Trevor holds a PhD from University College Dublin, Ireland.

@ThingsExpo Stories
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices t...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.