單元測試過濾器
過濾程式碼:
angular.module('myModule', []).filter('multiplier', function() {
return function(number, multiplier) {
if (!angular.isNumber(number)) {
throw new Error(number + " is not a number!");
}
if (!multiplier) {
multiplier = 2;
}
return number * multiplier;
}
});
考試:
describe('multiplierFilter', function() {
var filter;
beforeEach(function() {
module('myModule');
inject(function(multiplierFilter) {
filter = multiplierFilter;
});
});
it('multiply by 2 by default', function() {
expect(filter(2)).toBe(4);
expect(filter(3)).toBe(6);
});
it('allow to specify custom multiplier', function() {
expect(filter(2, 4)).toBe(8);
});
it('throws error on invalid input', function() {
expect(function() {
filter(null);
}).toThrow();
});
});
備註: 在測試中的 inject
呼叫中,需要通過名稱+ Filter 指定過濾器。原因是無論何時為模組註冊過濾器,Angular 都會在其名稱後附加 Filter
進行註冊。