Skip to content

Commit

Permalink
feat(rules): add rule for invoking @Injectable()
Browse files Browse the repository at this point in the history
Fix #70
  • Loading branch information
mgechev committed Sep 25, 2016
1 parent 49e3000 commit c84df93
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/invokeInjectableRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as Lint from 'tslint/lib/lint';
import * as ts from 'typescript';
import {sprintf} from 'sprintf-js';
import {Ng2Walker} from './angular/ng2Walker';

export class Rule extends Lint.Rules.AbstractRule {
static FAILURE_STRING: string = 'You have to invoke @Injectable()';

public apply(sourceFile:ts.SourceFile):Lint.RuleFailure[] {
return this.applyWithWalker(
new ValidateInjectableWalker(sourceFile,
this.getOptions()));
}
}

export class ValidateInjectableWalker extends Ng2Walker {
visitClassDeclaration(declaration: ts.ClassDeclaration) {
(<ts.Decorator[]>declaration.decorators || [])
.forEach((d: any) => {
// This means that "Injectable" is used as Identifier,
// not as a call expression.
if (d.expression && d.expression.text === 'Injectable') {
this.addFailure(this.createFailure(d.getStart(), d.getWidth(), Rule.FAILURE_STRING));
}
});
}
}
78 changes: 78 additions & 0 deletions test/invokeInjectableRule.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {assertFailure, assertSuccess} from './testHelper';

describe('invoke-injectable', () => {
describe('success', () => {
it('should not fail when no decorator is set', () => {
let source = 'class Foobar {}';
assertSuccess('invoke-injectable', source);
});

it('should not fail when different decorator is used', () => {
let source = `
@Component()
@Wove
class Foobar {
foo() {}
}
`;
assertSuccess('invoke-injectable', source);
});

it('should not fail when injectable is invoked', () => {
let source = `
@Injectable()
class Foobar {
foo() {}
}
`;
assertSuccess('invoke-injectable', source);
});

});

describe('failure', () => {

it('should fail when injectable is not invoked', () => {
let source = `
@Injectable
class Foobar {
foo() {}
}
`;
assertFailure('invoke-injectable', source, {
message: 'You have to invoke @Injectable()',
startPosition: {
line: 1,
character: 8
},
endPosition: {
line: 1,
character: 19
}
});
});

it('should fail when injectable is not invoked and multiple decorators are used', () => {
let source = `
@Injectable
@Component()
class Foobar {
foo() {}
}
`;
assertFailure('invoke-injectable', source, {
message: 'You have to invoke @Injectable()',
startPosition: {
line: 1,
character: 8
},
endPosition: {
line: 1,
character: 19
}
});
});

});
});

0 comments on commit c84df93

Please sign in to comment.