UNPKG

3.15 kBJavaScriptView Raw
1/**
2 * unittest `inject` functions should only consist of assignments from injected values to describe block variables
3 *
4 * `inject` functions in unittests should only contain a sorted mapping of injected values to values in the `describe` block with matching names.
5 * This way the dependency injection setup is separated from the other setup logic, improving readability of the test.
6 *
7 * @version 0.15.0
8 * @category conventions
9 * @sinceAngularVersion 1.x
10 */
11'use strict';
12
13var angularRule = require('./utils/angular-rule');
14
15
16module.exports = {
17 meta: {
18 schema: []
19 },
20 create: angularRule(function(context) {
21 function report(node, name) {
22 context.report(node, 'inject functions may only consist of assignments in the form {{name}} = _{{name}}_', {
23 name: name || 'myService'
24 });
25 }
26
27 return {
28 'angular?inject': function(callExpression, fn) {
29 if (!fn) {
30 return;
31 }
32 var valid = [];
33 // Report bad statement types
34 fn.body.body.forEach(function(statement) {
35 if (statement.type !== 'ExpressionStatement') {
36 return report(statement);
37 }
38 if (statement.expression.type !== 'AssignmentExpression') {
39 return report(statement);
40 }
41 if (statement.expression.right.type !== 'Identifier') {
42 return report(statement);
43 }
44 // From this point there is more context on what to report.
45 var name = statement.expression.right.name.replace(/^_(.+)_$/, '$1');
46 if (statement.expression.left.type !== 'Identifier') {
47 return report(statement, name);
48 }
49 if (statement.expression.right.name !== '_' + name + '_') {
50 return report(statement, name);
51 }
52 if (statement.expression.left.name !== name) {
53 return report(statement, name);
54 }
55 // Register valid statements for sort order validation
56 valid.push(statement);
57 });
58 // Validate the sorting order
59 var lastValid;
60 valid.forEach(function(statement) {
61 if (!lastValid) {
62 lastValid = statement.expression.left.name;
63 return;
64 }
65 if (statement.expression.left.name.localeCompare(lastValid) !== -1) {
66 lastValid = statement.expression.left.name;
67 return;
68 }
69 context.report(statement, "'{{current}}' must be sorted before '{{previous}}'", {
70 current: statement.expression.left.name,
71 previous: lastValid
72 });
73 });
74 }
75 };
76 })
77};