Beginning AngularJS

(WallPaper) #1

Chapter 10 ■ Deployment ConsiDerations


Starting off by writing a set of unit tests like this is a great way to get you thinking about what aspects of the code
will need to be tested. It’s perfectly fine just to start writing these out as the project requirements and use cases for a
feature start to evolve.
This particular framework, called Jasmine, uses a describe function that itself contains several it functions. The
describe function describes, through its first parameter, the purpose of the tests contained within; it’s really just a title
describing this particular set of unit tests. As these tests all pertain to the user login form, we named it user login form.
Its second parameter is a function, and it is this function that contains the individual unit tests; the it() methods.
The it() methods’ first parameter explains its purpose; this needs to be clear and descriptive. Its second
parameter is a function; that is, the test itself. So that we can get a basic sense of what a test looks like, I will add some
code to the “ensures valid email addresses pass validation test,” which is the test described in the second it() method
in Listing 10-6.


Listing 10-6. The “ensures valid email addresses pass validation test”


it('ensures valid email addresses pass validation', function() {
var validEmails = [
'[email protected]',
'[email protected]',
'[email protected]'
];


for (var i in validEmails) {
var valid = LoginService.isValidEmail(validEmails[i]);
expect(valid).toBeTruthy();
}


});


The test in Listing 10-6, as you can tell by its name, ensures valid email addresses pass validation. The most
important statement is the one that has been set in bold. Here we use the expect() method to set up an expectation.
This is chained to the toBeTruthy() matcher method. This statement will bring about the success or failure of the test.
Should any of the email addresses in the validEmails array be invalid, this test will fail; otherwise, it will pass.
This pattern of having an expectation that is chained to a matcher is a very intuitive way to assert whether or
not any given test should be deemed a success or a failure. A few examples, shown in Listing 10-7, should show the
general pattern and a few of the expectations and matchers that come with the Jasmine unit test framework.


Listing 10-7. Sample expectations and matchers


// We expect 1 + 1 to equal 2.
// If it doesn’t the test fails
expect(1 + 1).toEqual(2);


// We expect myObject to be null.
// If its not the test fails
var myObject = null;
expect(myObject).toBe(null);


// We expect null to be null
// If its not the test fails
expect(null).toBeNull();

Free download pdf