UNPKG

2.1 kBJavaScriptView Raw
1'use strict';
2
3const astUtil = require('../util/ast');
4const { additionalSuiteNames } = require('../util/settings');
5
6function newDescribeLayer(describeNode) {
7 return {
8 describeNode,
9 hookNodes: [],
10 testCount: 0
11 };
12}
13
14module.exports = function (context) {
15 const options = context.options[0] || {};
16 const allowedHooks = options.allow || [];
17 const settings = context.settings;
18 const layers = [];
19
20 function popLayer(node) {
21 const layer = layers[layers.length - 1];
22 if (layer.describeNode === node) {
23 if (layer.testCount <= 1) {
24 layer.hookNodes
25 .filter(function (hookNode) {
26 return allowedHooks.indexOf(hookNode.name) === -1;
27 })
28 .forEach(function (hookNode) {
29 context.report({
30 node: hookNode,
31 message: `Unexpected use of Mocha \`${ hookNode.name }\` hook for a single test case`
32 });
33 });
34 }
35 layers.pop();
36 }
37 }
38
39 return {
40 Program(node) {
41 layers.push(newDescribeLayer(node));
42 },
43
44 CallExpression(node) {
45 if (astUtil.isDescribe(node, additionalSuiteNames(settings))) {
46 layers[layers.length - 1].testCount += 1;
47 layers.push(newDescribeLayer(node));
48 return;
49 }
50
51 if (astUtil.isTestCase(node)) {
52 layers[layers.length - 1].testCount += 1;
53 }
54
55 if (astUtil.isHookIdentifier(node.callee)) {
56 layers[layers.length - 1].hookNodes.push(node.callee);
57 }
58 },
59
60 'CallExpression:exit': popLayer,
61 'Program:exit': popLayer
62 };
63};
64
65module.exports.schema = [
66 {
67 type: 'object',
68 properties: {
69 allow: {
70 type: 'array',
71 items: {
72 type: 'string'
73 }
74 }
75 }
76 }
77];