Skip to content

Commit

Permalink
fix(rule): prevent error when parent class node does not exist
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinbuhmann committed Apr 25, 2018
1 parent f862454 commit 3e355c4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
15 changes: 3 additions & 12 deletions src/noLifeCycleCallRule.ts
Expand Up @@ -14,7 +14,7 @@ export class Rule extends Lint.Rules.AbstractRule {
typescriptOnly: true,
};

static FAILURE_STRING: string = 'Avoid explicitly calls to lifecycle hooks in class "%s"';
static FAILURE_STRING: string = 'Avoid explicit calls to lifecycle hooks.';

public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new ExpressionCallMetadataWalker(sourceFile, this.getOptions()));
Expand Down Expand Up @@ -55,17 +55,8 @@ export class ExpressionCallMetadataWalker extends NgWalker {
const isSuperCall = expression && expression.kind === ts.SyntaxKind.SuperKeyword;
const isLifecycleCall = name && ts.isIdentifier(name) && lifecycleHooksMethods.has(name.text as any);

if (isSuperCall || !isLifecycleCall) {
return;
if (isLifecycleCall && !isSuperCall) {
this.addFailureAtNode(node, Rule.FAILURE_STRING);
}

let currentNode = node as any;

while (currentNode.parent.parent) {
currentNode = currentNode.parent;
}

const failureConfig = [Rule.FAILURE_STRING, currentNode.name.text];
this.addFailureAtNode(node, sprintf.apply(this, failureConfig));
}
}
25 changes: 24 additions & 1 deletion test/noLifeCycleCallRule.spec.ts
Expand Up @@ -61,13 +61,36 @@ describe(ruleName, () => {
it(`should fail when explicitly calling ${lifecycleHookMethodCall}`, () => {
assertAnnotated({
ruleName,
message: `Avoid explicitly calls to lifecycle hooks in class "${className}"`,
message: 'Avoid explicit calls to lifecycle hooks.',
source
});
});
});
});
}

lifecycleHooksMethods.forEach(lifecycleHookMethod => {
const lifecycleHookMethodCall = `fixture.componentInstance.${lifecycleHookMethod}()`;
const totalTildes = '~'.repeat(lifecycleHookMethodCall.length);
const source = `
it('should work', () => {
// test code...
${lifecycleHookMethodCall}
${totalTildes}
// more test code...
})
`;

it(`should fail when explicitly calling ${lifecycleHookMethod} outside of a class`, () => {
assertAnnotated({
ruleName,
message: `Avoid explicit calls to lifecycle hooks.`,
source
});
});
});
});

describe('success', () => {
Expand Down

0 comments on commit 3e355c4

Please sign in to comment.