Testing AngularJS From Scratch - p-patel/software-engineer-knowledge-base GitHub Wiki
https://app.pluralsight.com/library/courses/testing-angularjs-from-scratch/
Getting Started
Getting the Software
- Jasmine, test framework; Karma, test runner
BDD and AngularJS
...
Spy vs. Spy
Introduction
- Matchers - e.g.
toBe()
. Can create custom matchers - Jasmine spies - aka doubles, fakes, mocks
Refactoring
- removed expense.js; expenseItem object constructor updated to accept parameters to specify type, description and amount expenseItem.js now returns an array of ExpenseItem instead of anonymous objects
Custom Matchers
- e.g. for the test
expect(taxi).toBeLessThan(100);
- declare custom matchers in spec\SpecHelper.js:
var customMatchers = {
toBeAReasonableExpense: function(actual){
return {
compare: function(actual){
var pass = actual.isReasonable();
var judgement = pass ? "unreasonable" : "reasonable";
return {
pass: pass,
message: 'Expected expense to be a ' + judgement + ' expense.';
}
}
}
};
}
then, in spec (test) file:
beforeEach(function() {
jasmine.addMatchers(customMatchers);
});
...
...
expect(taxi).toBeAReasonableExpense();
- describe() can be nested
- to use negation of the custom matcher, use
expect(taxi).not.toBeAReasonableExpense();
Spies
- Jasmine feature: 'Spies' - e.g. test whether methods have been called and for creating mocks
var spyCallback = jasmine.createSpy('callBackSpy');
expensesDataService.persistExpenses(spyCallback);
expect(spyCallback).toHaveBeenCalled();
also,
var spy = spyOn(expensesDataService, 'persistExpenses');
expensesDataService.persistExpenses();
expect(spy).toHaveBeenCalled();
- can use spies to fake behaviour
- can use spies to create mocks:
var spy = spyOn(expensesDataService, 'persistExpenses').and.callFake(function(){
return 3;
});
var numberOfRecordsPersisted = expensesDataService.persistExpenses();
expect(numberOfRecordsPersisted).toEqual(3);