2 * @fileoverview Mocha test wrapper
7 /* global describe, it */
10 * This is a wrapper around mocha to allow for DRY unittests for eslint
12 * RuleTester.run("{ruleName}", {
15 * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} }
18 * { code: "{code}", errors: {numErrors} },
19 * { code: "{code}", errors: ["{errorMessage}"] },
20 * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] }
25 * {code} - String that represents the code to be tested
26 * {options} - Arguments that are passed to the configurable rules.
27 * {globals} - An object representing a list of variables that are
28 * registered as globals
29 * {parser} - String representing the parser to use
30 * {settings} - An object representing global settings for all rules
31 * {numErrors} - If failing case doesn't need to check error message,
32 * this integer will specify how many errors should be
34 * {errorMessage} - Message that is returned by the rule on failure
35 * {errorNodeType} - AST node type that is returned by they rule as
36 * a cause of the failure.
39 //------------------------------------------------------------------------------
41 //------------------------------------------------------------------------------
44 assert = require("assert"),
45 path = require("path"),
46 util = require("util"),
47 merge = require("lodash.merge"),
48 equal = require("fast-deep-equal"),
49 Traverser = require("../../lib/shared/traverser"),
50 { getRuleOptionsSchema, validate } = require("../shared/config-validator"),
51 { Linter, SourceCodeFixer, interpolate } = require("../linter");
53 const ajv = require("../shared/ajv")({ strictDefaults: true });
55 const espreePath = require.resolve("espree");
56 const parserSymbol = Symbol.for("eslint.RuleTester.parser");
58 //------------------------------------------------------------------------------
60 //------------------------------------------------------------------------------
62 /** @typedef {import("../shared/types").Parser} Parser */
65 * A test case that is expected to pass lint.
66 * @typedef {Object} ValidTestCase
67 * @property {string} code Code for the test case.
68 * @property {any[]} [options] Options for the test case.
69 * @property {{ [name: string]: any }} [settings] Settings for the test case.
70 * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
71 * @property {string} [parser] The absolute path for the parser.
72 * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
73 * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
74 * @property {{ [name: string]: boolean }} [env] Environments for the test case.
75 * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
79 * A test case that is expected to fail lint.
80 * @typedef {Object} InvalidTestCase
81 * @property {string} code Code for the test case.
82 * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
83 * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
84 * @property {any[]} [options] Options for the test case.
85 * @property {{ [name: string]: any }} [settings] Settings for the test case.
86 * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
87 * @property {string} [parser] The absolute path for the parser.
88 * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
89 * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
90 * @property {{ [name: string]: boolean }} [env] Environments for the test case.
91 * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
95 * A description of a reported error used in a rule tester test.
96 * @typedef {Object} TestCaseError
97 * @property {string | RegExp} [message] Message.
98 * @property {string} [messageId] Message ID.
99 * @property {string} [type] The type of the reported AST node.
100 * @property {{ [name: string]: string }} [data] The data used to fill the message template.
101 * @property {number} [line] The 1-based line number of the reported start location.
102 * @property {number} [column] The 1-based column number of the reported start location.
103 * @property {number} [endLine] The 1-based line number of the reported end location.
104 * @property {number} [endColumn] The 1-based column number of the reported end location.
107 //------------------------------------------------------------------------------
109 //------------------------------------------------------------------------------
112 * testerDefaultConfig must not be modified as it allows to reset the tester to
113 * the initial default configuration
115 const testerDefaultConfig = { rules: {} };
116 let defaultConfig = { rules: {} };
119 * List every parameters possible on a test case that are not related to eslint
122 const RuleTesterParameters = [
132 * All allowed property names in error objects.
134 const errorObjectParameters = new Set([
145 const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;
148 * All allowed property names in suggestion objects.
150 const suggestionObjectParameters = new Set([
156 const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;
158 const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
161 * Clones a given value deeply.
162 * Note: This ignores `parent` property.
163 * @param {any} x A value to clone.
164 * @returns {any} A cloned value.
166 function cloneDeeplyExcludesParent(x) {
167 if (typeof x === "object" && x !== null) {
168 if (Array.isArray(x)) {
169 return x.map(cloneDeeplyExcludesParent);
174 for (const key in x) {
175 if (key !== "parent" && hasOwnProperty(x, key)) {
176 retv[key] = cloneDeeplyExcludesParent(x[key]);
187 * Freezes a given value deeply.
188 * @param {any} x A value to freeze.
191 function freezeDeeply(x) {
192 if (typeof x === "object" && x !== null) {
193 if (Array.isArray(x)) {
194 x.forEach(freezeDeeply);
196 for (const key in x) {
197 if (key !== "parent" && hasOwnProperty(x, key)) {
198 freezeDeeply(x[key]);
207 * Replace control characters by `\u00xx` form.
208 * @param {string} text The text to sanitize.
209 * @returns {string} The sanitized text.
211 function sanitize(text) {
213 /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
214 c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
219 * Define `start`/`end` properties as throwing error.
220 * @param {string} objName Object name used for error messages.
221 * @param {ASTNode} node The node to define.
224 function defineStartEndAsError(objName, node) {
225 Object.defineProperties(node, {
228 throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`);
235 throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`);
245 * Define `start`/`end` properties of all nodes of the given AST as throwing error.
246 * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
247 * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
250 function defineStartEndAsErrorInTree(ast, visitorKeys) {
251 Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") });
252 ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
253 ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
257 * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
258 * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
259 * @param {Parser} parser Parser object.
260 * @returns {Parser} Wrapped parser object.
262 function wrapParser(parser) {
264 if (typeof parser.parseForESLint === "function") {
266 [parserSymbol]: parser,
267 parseForESLint(...args) {
268 const ret = parser.parseForESLint(...args);
270 defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
277 [parserSymbol]: parser,
279 const ast = parser.parse(...args);
281 defineStartEndAsErrorInTree(ast);
287 //------------------------------------------------------------------------------
289 //------------------------------------------------------------------------------
291 // default separators for testing
292 const DESCRIBE = Symbol("describe");
293 const IT = Symbol("it");
294 const IT_ONLY = Symbol("itOnly");
297 * This is `it` default handler if `it` don't exist.
299 * @param {string} text The description of the test case.
300 * @param {Function} method The logic of the test case.
301 * @returns {any} Returned value of `method`.
303 function itDefaultHandler(text, method) {
305 return method.call(this);
307 if (err instanceof assert.AssertionError) {
308 err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
315 * This is `describe` default handler if `describe` don't exist.
317 * @param {string} text The description of the test case.
318 * @param {Function} method The logic of the test case.
319 * @returns {any} Returned value of `method`.
321 function describeDefaultHandler(text, method) {
322 return method.call(this);
328 * Creates a new instance of RuleTester.
329 * @param {Object} [testerConfig] Optional, extra configuration for the tester
331 constructor(testerConfig) {
334 * The configuration to use for this tester. Combination of the tester
335 * configuration and the default configuration.
338 this.testerConfig = merge(
342 { rules: { "rule-tester/validate-ast": "error" } }
346 * Rule definitions to define before tests.
350 this.linter = new Linter();
354 * Set the configuration to use for all future tests
355 * @param {Object} config the configuration to use.
358 static setDefaultConfig(config) {
359 if (typeof config !== "object") {
360 throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
362 defaultConfig = config;
364 // Make sure the rules object exists since it is assumed to exist later
365 defaultConfig.rules = defaultConfig.rules || {};
369 * Get the current configuration used for all tests
370 * @returns {Object} the current configuration
372 static getDefaultConfig() {
373 return defaultConfig;
377 * Reset the configuration to the initial configuration of the tester removing
378 * any changes made until now.
381 static resetDefaultConfig() {
382 defaultConfig = merge({}, testerDefaultConfig);
387 * If people use `mocha test.js --watch` command, `describe` and `it` function
388 * instances are different for each execution. So `describe` and `it` should get fresh instance
391 static get describe() {
394 (typeof describe === "function" ? describe : describeDefaultHandler)
398 static set describe(value) {
399 this[DESCRIBE] = value;
405 (typeof it === "function" ? it : itDefaultHandler)
409 static set it(value) {
414 * Adds the `only` property to a test to run it in isolation.
415 * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
416 * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
419 if (typeof item === "string") {
420 return { code: item, only: true };
423 return { ...item, only: true };
426 static get itOnly() {
427 if (typeof this[IT_ONLY] === "function") {
428 return this[IT_ONLY];
430 if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
431 return Function.bind.call(this[IT].only, this[IT]);
433 if (typeof it === "function" && typeof it.only === "function") {
434 return Function.bind.call(it.only, it);
437 if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
439 "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
440 "See https://eslint.org/docs/developer-guide/nodejs-api#customizing-ruletester for more."
443 if (typeof it === "function") {
444 throw new Error("The current test framework does not support exclusive tests with `only`.");
446 throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
449 static set itOnly(value) {
450 this[IT_ONLY] = value;
454 * Define a rule for one particular run of tests.
455 * @param {string} name The name of the rule to define.
456 * @param {Function} rule The rule definition.
459 defineRule(name, rule) {
460 this.rules[name] = rule;
464 * Adds a new rule test to execute.
465 * @param {string} ruleName The name of the rule to run.
466 * @param {Function} rule The rule to test.
468 * valid: (ValidTestCase | string)[],
469 * invalid: InvalidTestCase[]
470 * }} test The collection of tests to run.
473 run(ruleName, rule, test) {
475 const testerConfig = this.testerConfig,
476 requiredScenarios = ["valid", "invalid"],
478 linter = this.linter;
480 if (!test || typeof test !== "object") {
481 throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
484 requiredScenarios.forEach(scenarioType => {
485 if (!test[scenarioType]) {
486 scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
490 if (scenarioErrors.length > 0) {
492 `Test Scenarios for rule ${ruleName} is invalid:`
493 ].concat(scenarioErrors).join("\n"));
497 linter.defineRule(ruleName, Object.assign({}, rule, {
499 // Create a wrapper rule that freezes the `context` properties.
501 freezeDeeply(context.options);
502 freezeDeeply(context.settings);
503 freezeDeeply(context.parserOptions);
505 return (typeof rule === "function" ? rule : rule.create)(context);
509 linter.defineRules(this.rules);
512 * Run the rule for the given item
513 * @param {string|Object} item Item to run the rule against
514 * @returns {Object} Eslint run result
517 function runRuleForItem(item) {
518 let config = merge({}, testerConfig),
519 code, filename, output, beforeAST, afterAST;
521 if (typeof item === "string") {
527 * Assumes everything on the item is a config except for the
528 * parameters used by this tester
530 const itemConfig = { ...item };
532 for (const parameter of RuleTesterParameters) {
533 delete itemConfig[parameter];
537 * Create the config object from the tester config and this item
538 * specific configurations.
547 filename = item.filename;
550 if (hasOwnProperty(item, "options")) {
551 assert(Array.isArray(item.options), "options must be an array");
552 config.rules[ruleName] = [1].concat(item.options);
554 config.rules[ruleName] = 1;
557 const schema = getRuleOptionsSchema(rule);
561 * The goal is to check whether or not AST was modified when
562 * running the rule under test.
564 linter.defineRule("rule-tester/validate-ast", () => ({
566 beforeAST = cloneDeeplyExcludesParent(node);
568 "Program:exit"(node) {
573 if (typeof config.parser === "string") {
574 assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
576 config.parser = espreePath;
579 linter.defineParser(config.parser, wrapParser(require(config.parser)));
582 ajv.validateSchema(schema);
585 const errors = ajv.errors.map(error => {
586 const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
588 return `\t${field}: ${error.message}`;
591 throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
595 * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
596 * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
597 * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
598 * the schema is compiled here separately from checking for `validateSchema` errors.
603 throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
607 validate(config, "rule-tester", id => (id === ruleName ? rule : null));
610 const messages = linter.verify(code, config, filename);
611 const fatalErrorMessage = messages.find(m => m.fatal);
613 assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
615 // Verify if autofix makes a syntax error or not.
616 if (messages.some(m => m.fix)) {
617 output = SourceCodeFixer.applyFixes(code, messages).output;
618 const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
620 assert(!errorMessageInFix, [
621 "A fatal parsing error occurred in autofix.",
622 `Error: ${errorMessageInFix && errorMessageInFix.message}`,
634 afterAST: cloneDeeplyExcludesParent(afterAST)
639 * Check if the AST was changed
640 * @param {ASTNode} beforeAST AST node before running
641 * @param {ASTNode} afterAST AST node after running
645 function assertASTDidntChange(beforeAST, afterAST) {
646 if (!equal(beforeAST, afterAST)) {
647 assert.fail("Rule should not modify AST.");
652 * Check if the template is valid or not
653 * all valid cases go through this
654 * @param {string|Object} item Item to run the rule against
658 function testValidTemplate(item) {
659 const result = runRuleForItem(item);
660 const messages = result.messages;
662 assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
664 util.inspect(messages)));
666 assertASTDidntChange(result.beforeAST, result.afterAST);
670 * Asserts that the message matches its expected value. If the expected
671 * value is a regular expression, it is checked against the actual
673 * @param {string} actual Actual value
674 * @param {string|RegExp} expected Expected value
678 function assertMessageMatches(actual, expected) {
679 if (expected instanceof RegExp) {
681 // assert.js doesn't have a built-in RegExp match function
683 expected.test(actual),
684 `Expected '${actual}' to match ${expected}`
687 assert.strictEqual(actual, expected);
692 * Check if the template is invalid or not
693 * all invalid cases go through this.
694 * @param {string|Object} item Item to run the rule against
698 function testInvalidTemplate(item) {
699 assert.ok(item.errors || item.errors === 0,
700 `Did not specify errors for an invalid test of ${ruleName}`);
702 if (Array.isArray(item.errors) && item.errors.length === 0) {
703 assert.fail("Invalid cases must have at least one error");
706 const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
707 const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;
709 const result = runRuleForItem(item);
710 const messages = result.messages;
712 if (typeof item.errors === "number") {
714 if (item.errors === 0) {
715 assert.fail("Invalid cases must have 'error' value greater than 0");
718 assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
720 item.errors === 1 ? "" : "s",
722 util.inspect(messages)));
725 messages.length, item.errors.length, util.format(
726 "Should have %d error%s but had %d: %s",
728 item.errors.length === 1 ? "" : "s",
730 util.inspect(messages)
734 const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
736 for (let i = 0, l = item.errors.length; i < l; i++) {
737 const error = item.errors[i];
738 const message = messages[i];
740 assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
742 if (typeof error === "string" || error instanceof RegExp) {
744 // Just an error message.
745 assertMessageMatches(message.message, error);
746 } else if (typeof error === "object" && error !== null) {
750 * This may have a message, messageId, data, node type, line, and/or
754 Object.keys(error).forEach(propertyName => {
756 errorObjectParameters.has(propertyName),
757 `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
761 if (hasOwnProperty(error, "message")) {
762 assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
763 assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
764 assertMessageMatches(message.message, error.message);
765 } else if (hasOwnProperty(error, "messageId")) {
768 "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
770 if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
771 assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
776 `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
778 if (hasOwnProperty(error, "data")) {
781 * if data was provided, then directly compare the returned message to a synthetic
782 * interpolated message using the same message ID and data provided in the test.
783 * See https://github.com/eslint/eslint/issues/9890 for context.
785 const unformattedOriginalMessage = rule.meta.messages[error.messageId];
786 const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
791 `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
797 hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
798 "Error must specify 'messageId' if 'data' is used."
802 assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
805 if (hasOwnProperty(error, "line")) {
806 assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
809 if (hasOwnProperty(error, "column")) {
810 assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
813 if (hasOwnProperty(error, "endLine")) {
814 assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
817 if (hasOwnProperty(error, "endColumn")) {
818 assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
821 if (hasOwnProperty(error, "suggestions")) {
823 // Support asserting there are no suggestions
824 if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
825 if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
826 assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
829 assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
830 assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
832 error.suggestions.forEach((expectedSuggestion, index) => {
834 typeof expectedSuggestion === "object" && expectedSuggestion !== null,
835 "Test suggestion in 'suggestions' array must be an object."
837 Object.keys(expectedSuggestion).forEach(propertyName => {
839 suggestionObjectParameters.has(propertyName),
840 `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
844 const actualSuggestion = message.suggestions[index];
845 const suggestionPrefix = `Error Suggestion at index ${index} :`;
847 if (hasOwnProperty(expectedSuggestion, "desc")) {
849 !hasOwnProperty(expectedSuggestion, "data"),
850 `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
853 actualSuggestion.desc,
854 expectedSuggestion.desc,
855 `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
859 if (hasOwnProperty(expectedSuggestion, "messageId")) {
862 `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
865 hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
866 `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
869 actualSuggestion.messageId,
870 expectedSuggestion.messageId,
871 `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
873 if (hasOwnProperty(expectedSuggestion, "data")) {
874 const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
875 const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);
878 actualSuggestion.desc,
880 `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
885 !hasOwnProperty(expectedSuggestion, "data"),
886 `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
890 if (hasOwnProperty(expectedSuggestion, "output")) {
891 const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
893 assert.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
900 // Message was an unexpected type
901 assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
906 if (hasOwnProperty(item, "output")) {
907 if (item.output === null) {
911 "Expected no autofixes to be suggested"
914 assert.strictEqual(result.output, item.output, "Output is incorrect.");
920 "The rule fixed the code. Please add 'output' property."
924 // Rules that produce fixes must have `meta.fixable` property.
925 if (result.output !== item.code) {
927 hasOwnProperty(rule, "meta"),
928 "Fixable rules should export a `meta.fixable` property."
931 // Linter throws if a rule that produced a fix has `meta` but doesn't have `meta.fixable`.
934 assertASTDidntChange(result.beforeAST, result.afterAST);
938 * This creates a mocha test suite and pipes all supplied info through
939 * one of the templates above.
941 RuleTester.describe(ruleName, () => {
942 RuleTester.describe("valid", () => {
943 test.valid.forEach(valid => {
944 RuleTester[valid.only ? "itOnly" : "it"](
945 sanitize(typeof valid === "object" ? valid.code : valid),
947 testValidTemplate(valid);
953 RuleTester.describe("invalid", () => {
954 test.invalid.forEach(invalid => {
955 RuleTester[invalid.only ? "itOnly" : "it"](
956 sanitize(invalid.code),
958 testInvalidTemplate(invalid);
967 RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
969 module.exports = RuleTester;