Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Testing and Debugging<br />
• toContain(): This checks whether an element is part of an array. This is not<br />
an exact object match as toBe(). For example, look at the following code:<br />
expect([1, 2, 3]).toContain(3);<br />
expect("astronomy is a science").toContain("science");<br />
• toBeDefined() and toBeUndefined(): These two matches are handy to<br />
check whether a variable is undefined (or not).<br />
• toBeNull(): This checks whether a variable's value is null.<br />
• toBeGreaterThan() and toBeLessThan(): These matchers perform numeric<br />
comparisons (they work on strings too):<br />
expect(2).toBeGreaterThan(1);<br />
expect(1).toBeLessThan(2);<br />
expect("a").toBeLessThan("b");<br />
One interesting feature of Jasmine is the spies. When you are writing a large system,<br />
it is not possible to make sure that all systems are always available and correct. At<br />
the same time, you don't want your unit tests to fail due to a dependency that may be<br />
broken or unavailable. To simulate a situation where all dependencies are available<br />
for a unit of code that we want to test, we mock these dependencies to always give<br />
the response that we expect. Mocking is an important aspect of testing and most<br />
testing frameworks provide support for the mocking. Jasmine allows mocking using<br />
a feature called a spy. Jasmine spies essentially stub the functions that we may not<br />
have ready; at the time of writing the test case but as part of the functionality, we<br />
need to track that we are executing these dependencies and not ignoring them.<br />
Consider the following example:<br />
describe("mocking configurator", function() {<br />
var configurator = null;<br />
var responseJSON = {};<br />
beforeEach(function() {<br />
configurator = {<br />
submitPOSTRequest: function(payload) {<br />
//This is a mock service that will eventually be replaced<br />
//by a real service<br />
console.log(payload);<br />
return {"status": "200"};<br />
}<br />
};<br />
spyOn(configurator,<br />
'submitPOSTRequest').and.returnValue({"status": "200"});<br />
configurator.submitPOSTRequest({<br />
[ 152 ]<br />
www.it-ebooks.info